Answer the question
In order to leave comments, you need to log in
How to respect time zone when working with Moment.js?
Hello!
There was a problem with temporary zones of users. I spent the whole day to understand how Moment.js works and why it is so praised.
The problem is in the current date, for some reason it shows 1 hour less than it should be.
I set the global locale and time zone:
moment.locale('ru');
moment.tz.setDefault("Europe/Moscow");
var now = moment().format('MMMM Do YYYY, HH:mm:ss');
console.log(now) // получаю Февраль 3-го 2016, 02:36:51
var date = moment.utc('2016-01-05 12:00:00').format(); // Как-бы дата из прошлого
var converted = moment(date).format('MMMM Do YYYY, HH:mm:ss'); // Форматируем с учетом установленной глобальной временной зоны
console.log('было - ' + date + ', стало - ' + converted) // было - 2016-01-05 12:00:00, стало - 2016-01-05 15:00:00
moment.tz.guess();
abbr = abbr[0].match(/[A-Z]/g).join('');
Answer the question
In order to leave comments, you need to log in
The moment takes information about time and time zone from the OS. If it shows something wrong, then you have the time zone configured incorrectly in the OS.
Example: I changed tz to Paris (+01:00), but set the time to Moscow. If you request a moment of time, then it will give out what is installed in the system: 2016-02-03T04:08:24+01:00. The time coincides with Moscow, but the wrong tz. If you forcibly set the time zone at the very moment, then it will take the system time and tz and try to translate it into local time for the specified tz. Thus, if you set the Moscow tz and request the current time again, the moment will return 2016-02-03T06:13:17+03:00. Time has shifted, but tz is correct.
So you most likely have tz +04:00 in your system, so the hour is lost.
Well, yes, the time must be stored in UTC, and displayed on the page in accordance with the user's time zone. The time zone can be checked with the client himself.
You can find out the offset in minutes relative to UTC like this: moment().utcOffset()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question