Reputation: 4484
I'm trying to convert a unix timestamp to local time using moment.tz . I've noticed I have to use a format when passing in a date, like this
moment.tz(date, 'MM/DD/YYYY hh:mm a', zone).format('MM/DD/YYYY hh:mm a');
My problem is when I want to convert from a unix timestamp to calendar like date the conversion fails. What should I pass for the format string?
I've tried these two formats with no luck
var date = moment.tz(publishInterval.DateUnix, 'X', zone).format('MM/DD/YYYY hh:mm a');
var date = moment.tz(publishInterval.DateUnix, zone).format('MM/DD/YYYY hh:mm a');
Upvotes: 2
Views: 21117
Reputation: 1
I know I'm about 5 years late, but in case anyone stumbled upon this thread and was trying to figure out the answer, here it is...
I had to break down dates into unix time-stamps, so that I could properly .sort() them.
Here is how I converted them back:
let categories = ['2021-08-24', '2021-08-23', '2021-08-25', '2021-08-22', '2021-08-21', '2021-08-25', '2021-08-20']
//Convert to unix time-stamp looping through array of dates
for (let i = 0; i < categories.length; i++) {
let tempDate = moment(categories[i]).format();
categories[i] = moment(tempDate).unix();
}
categories.sort();
//Revert Back to 2021-08-24 looping through same array
for (let i = 0; i < categories.length; i++) {
let tempDate = moment.unix(categories[i]).format('YYYY-MM-DD hh:mm:ss:SSS a');
categories[i] = moment(tempDate).format('YYYY-MM-DD');
}
Upvotes: 0
Reputation: 43
I believe there is a very simple fix for this when using moment. Simply use the .unix function with moment. Below is an example -
var date = moment.unix(date).format("MM/DD/YYYY hh:mm a")
Upvotes: 3
Reputation: 1166
have you tried
moment(date).format('MM/DD/YYYY hh:mm a')
as is?
Upvotes: 5