7

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?

2
  • look at this stackoverflow.com/questions/4631928/… Commented May 6, 2014 at 0:08
  • @Vorge That solution assumes the epoch is in UTC which it is not in my case. Commented May 6, 2014 at 0:10

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.