简体   繁体   中英

moment.js format for unix timestamp?

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');

你试过moment(date).format('MM/DD/YYYY hh:mm a')吗?

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")

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'); }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM