Consistent Client Side Date/timestamp using JavaScript(considering TimeZones)

廉价感情. 提交于 2020-01-04 08:59:11

问题


My question is regarding this quote from the manual about dates in JavaScript:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.

new Date('2016-04-14') output for a user was Wed Apr 13 2016 17:00:00 GMT-0700 (US Mountain Standard Time) upon which he had to use .toUTCString().

How to handle this if the users are in many different time zones?


回答1:


new Date().getTime(); returns an integer value as the time on client's machine since 1970 Jan 1.

Since this is an integer value, it will be agnostic of locales, browser version, different browsers (IE, Chrome, Mozilla, or anything).

So, this should give you consistent results in terms of time on client's machine as long as client's timezone is known.

You can fetch client's timezone offset by using getTimezoneOffset API

var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;

This together with new Date().getTime(); should give you consistent results.




回答2:


If you use

 new Date().getTime();

it will return you a milisecond time stamp since 1970-01-01 for the current time zone that the client is in. This can then be converted back to a date in any language.

This would be a better standard way to pass the date around if you are sending it to and from servers and between clients. As millisecond timestamp ts converted in timezone a will convert to 01/01/2010 and in timezone b will convert to 01/01/2010 as they are taken from 1970-01-01

Hope this makes sence



来源:https://stackoverflow.com/questions/36590873/consistent-client-side-date-timestamp-using-javascriptconsidering-timezones

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