Should timestamps always use UTC?

南笙酒味 提交于 2019-12-04 04:58:26
tjg184

Timestamps should certainly be stored in UTC. How the date is formatted is dependent on the requirements for that timezone. Timestamps are generally stored in UTC so the conversion for display to other timezones is easier and possible.

By only storing timestamps as UTC in databases, you effectively make time zones a view concern only. All math and logic in regards to comparisons of times can be assumed to sync up world-wide. The rest is simply a matter of a client knowing where it's at, what the rules are for where it's at, and then just spitting out the result. In JavaScript via the Chrome developer's console for instance:

var dateObj = new Date();

console.log(dateObj);
//spits out local time
//if you and 23 other people in every time zone across the planet created
//a date object simultaneously you'd all see a different number
//adapted to your local time zones

var utcInMillis = dateObj.getTime();
//gives UTC in milliseconds.

console.log(utcInMillis);
//if you and 23 other people in every time zone across the planet created
//that same date object `dateObj` simultaneously you'd see the same number

console.log(new Date().getTime() - utcInMillis);
//how many milliseconds passed since utcinMillis was recorded and now

var utcAsDateObj = new Date(utcInMillis);
console.log(utcAsDateObj);
//and that's how easy it is to restore to a date
//object from a UTC in  millisecond format

Generally speaking, where there's modern web technology or similar options, the least painful thing to do is to store everything as UTC and then make time zones strictly a presentational concern. You don't need local time for anything but showing somebody time in the local context.

Even if you're stuck with some silly non-UTC timestamp on the back-end it's still worth making UTC your canonicalized option on the client-side by converting at point of entry and converting back at point of exit by whatever means possible. Sorting out time zones and in what places Daylight Savings Time was adopted and where its ignored is just way too much of a mess to DIY and it's typically inevitable if you actually have to touch the date object that you'll need to get a bit fancier with actually manipulating/comparing dates/times eventually.

There is no easier way to handle that than when everything is canonicalized as UTC in milliseconds right up the point before you spit it out on the page as a local time.

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