javascript - 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 -
这个还可以
我不确定我到底做错了什么?
解决方案
您需要删除行中的.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()
(默认格式)工作得很好。
推荐阅读
- node.js - Azure DevOps 为 Angular 构建管道并且无法执行构建脚本节点错误
- soap - 可以在 micronaut 中创建 SOAP 服务吗?
- c++ - 将大整数作为向量中的值传递时出现分段错误
- python - 如何设置带有线程的bottlepy以在后台处理
- git - 如何检查本地分支是否与远程分支同步?
- hbase - 如何中止/终止 HBase 中的过程
- javascript - 如何在 popup.js 和 background.js 之间进行正确的消息传递?
- mongodb - 如何在 React Native 的 Return 中编写 JSX 代码?
- java - 是否总是需要在方法中编写 try-catch(),静态 void main() 是方法,是的,静态 void main() 是方法?
- c++ - 如何使用着色器为directX11中的对象添加不透明度