Reputation: 5261
I have a list of international events with their start dates stored in unix timestamp format. I would like to convert these to the user's local time using moment.js. I am attempting to do this using:
var example_utc = 1628946000;
// GMT: Saturday, August 14, 2021 1:00:00 PM
// Your time zone: Saturday, August 14, 2021 2:00:00 PM GMT+01:00 DST
// Relative: In 6 days
moment(example_utc);
However, this returns:
Mon Jan 19 1970 20:19:37 GMT+0000
Any idea what I am doing wrong?
Upvotes: 0
Views: 1304
Reputation: 1276
Fisrt of all you need to get it as unix as momentJs right way. Then you can convert it as localDate by using .local() or automatic (situational):
var example_utc = 1628946000;
var momentStyle = moment.unix(example_utc);
var localDate = moment(momentStyle).local();
alert(localDate); // Sat Aug 14 2021 17:00:00 GMT+0400
Also note that if your original input contains a time zone offset such as +00:00 or Z, you don't need to use .utc() or .local().
var example_utc = 1628946000;
var localDate = moment.unix(example_utc);
alert(localDate); // Sat Aug 14 2021 17:00:00 GMT+0400
Upvotes: 0
Reputation: 636
Multiply the UNIX timestamp to 1000 to convert it to milliseconds because javascript Date
works on milliseconds refer
var example_utc = 1628946000;
moment(example_utc*1000); // Saturday, August 14, 2021 1:00:00 PM
Upvotes: 1