Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 488
styfle Avatar asked May 05 '14 23:05

styfle


1 Answers

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.

like image 114
ryenus Avatar answered Oct 22 '22 23:10

ryenus