简体   繁体   中英

Convert unix timestamp with a timezone to javascript date

I have a legacy web app that stores dates as a UNIX timestamp (seconds since the epoch 1970). Usually a timestamp like this represents UTC, however these timestamps are UTC-8. It doesn't look like it ever accounts for Daylight Savings Time (DST). I could convert it on the server to UTC and send to the client, but I would like to know if there is a javascript only solution.

Example Input:

1399335987

Example Output:

"2014-05-05T16:26:27-07:00" // Pacific Daylight Time (PDT)

The client should display the date/time according to their local machine. I looked into using momentjs but I could not find how to construct a date from a number without the number being UTC already. Is this possible?

Yes, it's possible given the unix timestamps are in UTC, with Moment Timezone ( http://momentjs.com/timezone/ )

moment
  .unix(1399335987)
  .tz('MST')
  .format('YYYY-MM-DDTHH:mm:ssZ');

And you get

  "2014-05-05T17:26:27-07:00"

Note here I'm using MST , and you should be able to use whatever timezone you want, via Timezone Data Builder ( http://momentjs.com/timezone/data/ )

Actually, by default, moment parses and displays in local time.

This means, only if you're in a different timezone (offset really) and still want to get the local time in MST, it's necessary to set the timezone as MST.

Otherwise, moment.unix(1399335987).format('YYYY-MM-DDTHH:mm:ssZ') is good to go.

If you're absolutely certain that the values are seconds since 1970-01-01 UTC-8, then simply add 8 hours.

var dt = new Date((1399335987 * 1000) + (8 * 60 * 60 * 1000));

Or as a moment:

var m = moment.unix(1399335987).add(8, 'hours');
var s = m.format(); // for the ISO output with offset as you requested

However, it's quite odd that your timestamps would be fixed to UTC-8. If they were recorded in the US Pacific time zone, then they would reflect UTC-8 in the winter, and UTC-7 in the summer. You might be able to account for that, except you'll potentially have errors for any values that fall into the DST fall-back transition, as the hour from 1:00:00 - 1:59:59 is repeated.

Also, as a general rule - it's bad form to ever send out a numeric timestamp that is not based on the unix epoch. While you can correct for it in your own code, if you at all plan to share your data with others, then you should correct it on the server. (Ideally, send out an ISO8601 string, and not a timestamp at all.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM