javascript 解析 JSON (ISO8601) 日期字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11843704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:31:49  来源:igfitidea点击:

Parse JSON (ISO8601) date string

javascriptdateiso8601

提问by bobdev

I can create a JavaScript date object with:

我可以创建一个 JavaScript 日期对象:

var d=new Date('2012-08-07T07:47:46Z');
document.write(d);

This will write the date using the browser's time zone. But I should be able to do (no 'Z'):

这将使用浏览器的时区写入日期。但我应该能够做到(没有“Z”):

var d=new Date('2012-08-07T07:47:46');
document.write(d);

This returns the same as above, but according to the ISO8601 standard, a string without a timezone (e.g. +01:00) and without 'Z', the date should be considered in the local time zone. So the second example above should write the datetime as 7:47am.

这返回与上述相同,但根据 ISO8601 标准,一个没有时区(例如 +01:00)且没有 'Z' 的字符串,日期应考虑在本地时区。所以上面的第二个例子应该将日期时间写为早上 7:47。

I am getting a datetime string from a server and I want to display exactly that datetime. Any ideas?

我从服务器获取日期时间字符串,我想准确显示该日期时间。有任何想法吗?

回答by jrue

I found this script works well. It extends the Date.parse method.

我发现这个脚本运行良好。它扩展了 Date.parse 方法。

https://github.com/csnover/js-iso8601/

https://github.com/csnover/js-iso8601/

Date.parse('2012-08-07T07:47:46');

It doesn't work on the new Date()constructor however.

但是,它不适用于new Date()构造函数。

回答by Pran

You are right, Javascript doesn't play well with the ISO8601.

你是对的,Javascript 不能很好地与 ISO8601 配合使用。

Use this function to convert to the desired format:

使用此函数转换为所需的格式:

function ISODateString(d) {
  function pad(n){
    return n<10 ? '0'+n : n
  }
  return d.getUTCFullYear()+'-'
  + pad(d.getUTCMonth()+1)+'-'
  + pad(d.getUTCDate())+'T'
  + pad(d.getUTCHours())+':'
  + pad(d.getUTCMinutes())+':'
  + pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
print(ISODateString(d));

Taken from: Mozilla

摘自:Mozilla