1

I am getting timestamps for estimated bus arrival times from an API as a timestamp / epoch: 1536589019000. If I go to a website like this I get the appropriate format:

Monday, September 10, 2018 7:16:59 AM

But if I attempt to convert the date in javascript, for example, with momentjs, I get some date far into the future: 50662-08-08 08:03

moment.unix(estimatedArrivalTime).format("YYYY-MM-DD HH:mm")

How do I convert a unix timestamp properly?

mheavers
  • 29,530
  • 58
  • 194
  • 315
  • 2
    You're getting a timestamp in millesconds instead of seconds. Just passing it like so should work: `moment(1536589019000).format("YYYY-MM-DD HH:mm")` – Geert-Jan Sep 10 '18 at 14:13
  • Yep - I'll accept this if you post it (Had to also run parseInt, as for some reason the timestamp was coming back in generic format) – mheavers Sep 10 '18 at 14:14
  • The Unix timestamp counts the seconds since 1970-01-01, it's format is in seconds and not in milliseconds – Luca Kiebel Sep 10 '18 at 14:14
  • This is why people need to read docs. :) The millisecond and second with unix() is right beside each other. – epascarello Sep 10 '18 at 14:15

2 Answers2

2

divide the time by thousand , moment.unix() expects time to be in seconds

moment.unix(1536589019).format("YYYY-MM-DD HH:mm")
epascarello
  • 204,599
  • 20
  • 195
  • 236
ashish singh
  • 6,526
  • 2
  • 15
  • 35
  • https://momentjs.com/docs/#/parsing/unix-timestamp/ or use https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/ – epascarello Sep 10 '18 at 14:13
0

You're getting a timestamp in millesconds instead of seconds. Just passing it like so should work: moment(1536589019000).format("YYYY-MM-DD HH:mm")

Geert-Jan
  • 18,623
  • 16
  • 75
  • 137