将日期时间转换为 ISO 格式 [英] Convert datetime to ISO format

查看:197
本文介绍了将日期时间转换为 ISO 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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. 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

示例 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?

推荐答案

您的格式参数错误,请改用'DD.MM.YYYY H:mm:ss'.

没有小写dd,大写DD表示月份,大写YYYY表示年份而不是小写yyyy.

There is no lowercase dd, use uppercase DD for day of month and use uppercase YYYY for year instead of lowercase yyyy.

请注意toISOString():

请注意,.toISOString() 始终以 UTC 格式返回时间戳,即使相关时刻处于本地模式.这样做是为了与原生 JavaScript Date .toISOString() 的规范保持一致,如 ES2015 规范.

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>

这篇关于将日期时间转换为 ISO 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆