首页 > 解决方案 > Moment.js 麻烦将 unix 转换为本地时间到 utc

问题描述

嗨,我无法将时间戳从 unix 转换为本地到最终的 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;
}

例如我期待

convertToUTC(1594439125) //Actually Returns 07/10/2020 Expecting 07/11/2020 -这个错了

convertToUTC(1594393827) //Actually Returns 07/10/2020 Expecting 07/10/2020 -这个还可以

我不确定我到底做错了什么?

标签: javascriptmomentjs

解决方案


您需要删除行中的.format()部分convertToUTC ...。我不确定为什么,但格式化的时刻日期不会再次解析。所以:

let convertToUTC = (unixTimestamp)=> {

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

return UTC;
}

按预期工作。

PS 经过更多的挖掘,问题似乎是您在moment.unix(unixTimestamp)函数中使用的特定格式,因为moment.unix(unixTimestamp).format()(默认格式)工作得很好。


推荐阅读