Should timestamps always use UTC?

前端 未结 1 827
天涯浪人
天涯浪人 2021-02-14 04:57

Should timestamps always use UTC (as in 2012-06-14T10:32:11+00:00) and not local time (as in 2012-06-14T06:32:11-04:00 for New York)?

Referenc

相关标签:
1条回答
  • 2021-02-14 05:21

    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.

    0 讨论(0)
提交回复
热议问题