简体   繁体   English

使用D3.time.format进行解析时,date对象返回不同的日期

[英]date object returns different date when parsing using D3.time.format

var startDate = new Date('2013-05-13');
var date_format = d3.time.format("%m/%d");

if I do 如果我做

startDate = date_format(startDate); 

I get "05/12" instead of "05/13". 我得到的是“ 05/12”而不是“ 05/13”。 Anyone has a clue why is this happening? 有人知道为什么会这样吗?

Don't use the Date(string) constructor to parse dates; 不要使用Date(string)构造函数来解析日期; it varies from browser to browser. 随浏览器的不同而不同。 The most likely (but not guaranteed) interpretation of "2013-05-13" is as an ISO8601 string in UTC time. “ 2013-05-13”最可能(但不能保证)的解释是在UTC时间中作为ISO8601字符串。 Thus, if you run your statement in the JavaScript console, you will see: 因此,如果您在JavaScript控制台中运行语句,则会看到:

> new Date("2013-05-13")
Sun May 12 2013 17:00:00 GMT-0700 (PDT)

The string is interpreted in UTC time by the Date construct, while the returned Date object is in local time. 该字符串由Date构造以UTC时间解释,而返回的Date对象以本地时间表示。 May 13, midnight UTC is May 12 5PM PDT, so when you format it in local time using d3.time.format, you get back May 12. UTC的5月13日午夜是PDT 5月12日下午5点,因此,使用d3.time.format在本地时间对其进行格式化时,您将在5月12日返回。

You could switch to using d3.time.format.utc("%m/%d") to format your date, but then you're still dependent on the ambiguous behavior of the Date(string) constructor. 您可以切换到使用d3.time.format.utc("%m/%d")格式化日期,但随后您仍然依赖于Date(string)构造函数的歧义行为。 So, instead… 所以与其…

As @minikomi suggested, you could create a d3.time.format to parse a date string: d3.time.format("%Y-%m-%d") , then format.parse("2013-05-13") . 如@minikomi所建议的,您可以创建d3.time.format来解析日期字符串: d3.time.format("%Y-%m-%d") ,然后是format.parse("2013-05-13") Or you could use the multi-argument Date constructor: new Date(2013, 4, 13) , but note that months start at zero rather than the usual one. 或者,您可以使用多参数Date构造函数: new Date(2013, 4, 13) ,但请注意,月份从零开始而不是通常的一个月。

You might get more consistent results using a d3.time.format to parse your string as well: 您也可以使用d3.time.format解析字符串来获得更一致的结果:

  var startDate = '2013-05-13';
  var parser = d3.time.format("%Y-%m-%d");
  var formatter = d3.time.format("%m/%d");

  var startDateString = formatter(parser.parse(startDate));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM