Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting moment.js to show datetimes appropriate to info being viewed

Previous answers on here pointed me to moment.js for javascript date handling and I am really happy to find it. I can parse and manipulate quite happily.

The users on my website look at info relating to diverse physical sites/locations, and I want to show associated datetimes in the time specific to that location, not the users location.

Each physical site has a timezone attribute string like "Europe/London" or "Europe/Amsterdam"

My datetimes are all stored and delivered from the DB in UTC.

Is there a clever simple way I can render my moment.js object in any specified timezone?

like image 759
Aitch Avatar asked May 03 '12 20:05

Aitch


2 Answers

Theoretically, you could do something like this.

moment.fn.formatInZone = function(format, offset) {
    return this.clone().utc().add('hours', offset).format(format);
}

moment().formatInZone('HH:mm:ss', 7);
moment().formatInZone('HH:mm:ss', -7);

However, this requires that you know the correct offset, so it won't take into consideration daylight saving time.

like image 186
timrwood Avatar answered Nov 01 '22 12:11

timrwood


If you want to display dates in ANOTHER timezone than the user is actually in, then you need to start looking into stuff like https://bitbucket.org/pellepim/jstimezonedetect (if you need to detect which timezone a user is in) and https://github.com/mde/timezone-js if you need to localize dates between zones.

jsTimezoneDetect which I linked to above will help you provide a shortlist of relevant timezones.

That you have your datetimes stored in UTC will make it pretty damn easy for you thanks to mde/timezone-js.

like image 29
Jon Nylander Avatar answered Nov 01 '22 12:11

Jon Nylander