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

如果我做

startDate = date_format(startDate); 

我得到“05/12”而不是“05/13”。任何人都知道为什么会这样?

4

2 回答 2

5

Don’t use the Date(string) constructor to parse dates; 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. Thus, if you run your statement in the JavaScript console, you will see:

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

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. So, instead…</p>

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

于 2013-05-16T00:44:44.463 回答
2

您也可以使用 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));
于 2013-05-15T02:39:55.477 回答