[英]Convert datetime to ISO format
I have a date in format dd.MM.yyyy HH:mm:ss
and I need to convert it to ISO format, but it's not working correctly. 我有一个格式为dd.MM.yyyy HH:mm:ss
,我需要将其转换为ISO格式,但无法正常工作。 Here is my code: 这是我的代码:
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
example2: 例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
Where is the problem? 问题出在哪儿? Why do I get different results? 为什么会得到不同的结果?
Your format parameter is wrong, use 'DD.MM.YYYY H:mm:ss'
instead. 您的格式参数错误,请改用'DD.MM.YYYY H:mm:ss'
。
There is no lowercase dd
, use uppercase DD
for day of month and use uppercase YYYY
for year instead of lowercase yyyy
. 没有小写的dd
,在月中的一天使用大写DD
,在年份中使用大写的YYYY
而不是小写的yyyy
。
Please note that toISOString()
: 请注意toISOString()
:
Note that
.toISOString()
always returns a timestamp in UTC, even if the moment in question is in local mode. 请注意,即使有问题的时刻处于本地模式,.toISOString()
始终以UTC返回时间戳。 This is done to provide consistency with the specification for native JavaScript Date . 这样做是为了与本机JavaScript Date规范保持一致。toISOString()
, as outlined in the ES2015 specification .toISOString()
,如ES2015规范中所述 。
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>
In the second example, the parsed date results in December 1, 2016 0:00:00 (GMT+1) 在第二个示例中,解析日期为2016年12月1日0:00:00(GMT + 1)
When you output toISOString() it gives you the GMT time, which is 1 hour earlier, hence the November 30, 2016 23:00:00 当您输出到ISOString()时,它会为您提供格林尼治标准时间,比格林尼治标准时间早1小时,因此是2016年11月30日23:00:00
Look this link https://www.w3schools.com/js/js_date_formats.asp , paragraph 'ISO Dates' 查看此链接https://www.w3schools.com/js/js_date_formats.asp ,“ ISO日期”段落
Omitting T or Z in a date-time string can give different result in different browser. 在不同的浏览器中,在日期时间字符串中省略T或Z可以得出不同的结果。
I just tried using moment.js and it seems you used a mask as you'd use in C# for example. 我只是尝试使用moment.js,似乎您使用了掩码,例如在C#中使用的那样。 Moment.js uses capitals in the date parts. 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
The Date.parse()
function requires another kind of input. Date.parse()
函数需要另一种输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.