将日期时间转换为 ISO 格式

Convert datetime to ISO format

我有一个 dd.MM.yyyy HH:mm:ss 格式的日期,我需要将其转换为 ISO 格式,但它无法正常工作。 这是我的代码:

let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'dd.MM.yyyy HH:mm:ss')
console.log(parsedDate.toISOString()); //result is 2016-12-31T23:00:00.000Z

示例 2:

let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = new Date(date)
console.log(parsedDate.toISOString()); //result is 2016-11-30T23:00:00.000Z

问题出在哪里?为什么我得到不同的结果?

在第二个示例中,解析的日期结果为 2016 年 12 月 1 日 0:00:00 (GMT+1)

当您输出 toISOString() 时,它会为您提供 GMT 时间,该时间提前 1 小时,因此为 2016 年 11 月 30 日 23:00:00

看这个linkhttps://www.w3schools.com/js/js_date_formats.asp,段落'ISO Dates'

Omitting T or Z in a date-time string can give different result in different browser.

你的format parameter是错误的,请改用'DD.MM.YYYY H:mm:ss'

没有小写字母 dd,使用大写字母 DD 表示日期,使用大写字母 YYYY 表示年份而不是小写字母 yyyy

请注意toISOString():

Note that .toISOString() always returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString(), as outlined in the ES2015 specification.

let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'DD.MM.YYYY H:mm:ss')
console.log(parsedDate.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

我刚刚尝试使用 moment.js,您似乎使用了掩码,例如您在 C# 中使用的掩码。 Moment.js 在日期部分使用大写。

let date = '12.01.2016 0:00:00'; //12 January 2016
let parsedDate = moment(date, 'DD.MM.YYYY HH:mm:ss');
console.log(parsedDate.toISOString()); //result is 2016-01-11T23:00:00.000Z

Date.parse() 函数需要另一种输入。