Javascript convert between timezones with momentjs

只谈情不闲聊 提交于 2021-02-07 08:38:52

问题


in my app the user selects a date + time, and a timezone. This choice must be shown to other users IN THEIR OWN timezone, which means if user A from New York chooses August 8, 3:00 AM in EDT, user B from Beijing will see this datetime converted to China Standard Time (CST).

To do this I thought - ok I save user A's date and tell him to select out of 4 timezones. Server side I convert this from his EDT choice to UTC using moment timezone, and save it as UTC in the database, so that when I read it, I convert it back to other users according to their own timezones.

Is this a correct approach or am I overcomplicating things? THe purpose is that user A can choose her desired timezone, database saves as normalized UTC, target user sees in his own timezone.

(im using node.js for serverside btw) Thanks,


回答1:


Your approach is correct : save the time in UTC in the database and display it to the users according to their timezones.

momentjs can help you to do it but you need to give it the file of historical timezone changes.

check http://momentjs.com/timezone/ for further explanations.

once you have this, it is as easy as

var jun = moment("2014-06-01T12:00:00Z");
jun.tz('America/Los_Angeles').format('ha z');  // 5am PDT

also: don't store the user timezone as EDT, CST or -6. The hour shift can change with Summer times, Winter times, .. you need to store the Olson format, 'America/Los_Angeles'



来源:https://stackoverflow.com/questions/25470057/javascript-convert-between-timezones-with-momentjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!