1
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". Anyone has a clue why is this happening?

2 Answers 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…

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You might get more consistent results using a d3.time.format to parse your string as well:

  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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.