David Panart David Panart - 6 months ago 21
Javascript Question

How to get a worldwide valid timestamp

EDIT : I'm rewritting my post so it is clearer.

On my admin panel, I select a date from an Date input and send it to the server, which stock it in a MongoDB Date field. Before sending it, I change the date with a setHour(23,59,59,999), so that the countdown end at midnight (of wathever timezone, I do not care as long as it ends at the same soment for everyone in the world).

Then (I'm using Meteor), I query the fields, which is a Date object, I get its timestamp with a .getTime(), and every minute, thanks to an setInterval, I simply compute the time left with a new Date(), and output a hh:mm format.

BUT, when I put my pc on a different timezone, at the next interval computation, the value of time left is modified. And that's the same happening to my clients that are not in the same timezone, meaning the time left calculation is likely not done with absolute values.

Selecting the date :

Meteor.call("saveDate", new Date(new Date(t.find("#form_date").value).setHours(23,59,59,999)));

Saving it in mongo, server side :
saveDate: date => { DailyTopic.insert({ date: date }); };

Client calculation and display :

getTimeRemaining = function (limit) {
let endTime = new Date(limit).setHours(23, 59, 59, 999),
nowTime = Date.now();

let t = endTime - nowTime;

let seconds = Math.floor( (t/1000) % 60 ),
minutes = Math.floor( (t/1000/60) % 60 ),
hours = Math.floor( (t/(1000*60*60)) % 24 );

return ({
'hours' : hours,
'minutes' : minutes,
'seconds' : seconds

Template.debate.onCreated(function () {
let self = this;

self.timeLeft = new ReactiveVar(null);

self.limit = getTodayTopic('fetch');

self.interval = Meteor.setInterval(function () {
self.timeLeft.set( getTimeRemaining( getTodayTopic('fetch').date ) );
}, (1000 * 60));

setTimeout(function () {
self.timeLeft.set( getTimeRemaining( getTodayTopic('fetch').date ) );
}, 3000);


displayIimeLeft: function () {
let time = Template.instance().timeLeft.get(),
sp = " ";

if (time) {
return (time.hours + sp + TAPi18n.__('hours') + sp + time.minutes + sp + TAPi18n.__('minutes'));

But my problem is that the displayed countdown change according to the cliet timezone when I need it to be the same everywhere in the world !


You just need to create a Date Object of the limit date from your server, as you tagged Javascript, it would be done like this:

var time = new Date();

Then, add whatever time you need to that date object, which is the current time.

After that, you can compare that Date Object (Which has your servers timezone) with your clients Date (with their timezone)

That could be easily done with Moment.js:

moment(time).fromNow(); // E.g: in 24 Hours.

Actually this could be easily done without Moment.js too, but its up to you. The only trick is comparing dates with timezones on them.