我正在尝试获取 2018 年 1 月 1 日
moment("01-01-2018","MM-DD-YYYY").unix()
上述语句中的 1514745000
。但是当我尝试将它转换为 ISOString
时:
moment.unix(1514745000).toISOString()
归结为:2017-12-31T18:30:00.000Z
为什么会这样?为什么它不等于 2018-01-01T00:00:00.000Z
最佳答案
By default, moment parses and displays in local time.
Moment 默认使用本地时间,而 toISOString
输出为 UTC:
Note that
.toISOString()
returns a timestamp in UTC, even if the moment in question is in local mode.
如果您想将 "01-01-2018"
解析为 UTC,请使用 moment.utc
.
这里是一个例子,显示了在本地模式和 UTC 模式下解析的输出差异:
// Local 01-01-2018 : 1514761200 (UTC+01:00)
console.log( moment("01-01-2018","MM-DD-YYYY").unix() )
// UTC 01-01-2018: 1514764800
console.log( moment.utc("01-01-2018","MM-DD-YYYY").unix() )
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
您可以在 Local vs UTC vs Offset 中找到更多信息指导。
关于javascript - unix-timestamp 和 ISO 时间之间的关系。他们为什么不平等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48147121/