简体   繁体   中英

Moment.js trouble converting unix to local time to utc

Hi I am having trouble converting a timestamp from unix to local to ultimately utc.

let convertToUTC = (unixTimestamp)=> {

let convertedUnixToLocal = moment.unix(unixTimestamp).format("MM/DD/YYYY HH:mm:ss");
let UTC = moment.utc(convertedUnixToLocal).format("MM/DD/YYYY");

return UTC;
}

For example I am expecting

convertToUTC(1594439125) //Actually Returns 07/10/2020 Expecting 07/11/2020 - This one was wrong

convertToUTC(1594393827) //Actually Returns 07/10/2020 Expecting 07/10/2020 - This one was ok

I'm not sure what exactly I am doing wrong?

You need to remove the .format() part in your convertToUTC... line. I am not exactly sure why, but a formatted moment date doesn't parse again. So:

let convertToUTC = (unixTimestamp)=> {

let convertedUnixToLocal = moment.unix(unixTimestamp);
let UTC = moment.utc(convertedUnixToLocal).format("MM/DD/YYYY");

return UTC;
}

Works as expected.

PS After some more digging, it seems that the problem is the specific format that you are using in the moment.unix(unixTimestamp) function, as moment.unix(unixTimestamp).format() (default formatting) works just fine.

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