6

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?

styfle
  • 22,361
  • 27
  • 86
  • 128
  • look at this http://stackoverflow.com/questions/4631928/convert-utc-epoch-to-local-date-with-javascript – J261 May 06 '14 at 00:08
  • @Vorge That solution assumes the epoch is in UTC which it is not in my case. – styfle May 06 '14 at 00:10

1 Answers1

10

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.

ryenus
  • 15,711
  • 5
  • 56
  • 63