As per the instructions on this page: I am trying to parse an ISO 8601 date for use in D3.js. My test is almost word for word out of the post, I can't get it to work for a full date time string:
var format = d3.time.format("%Y-%m-%d");
alert(format.parse("2011-07-01T19:15:28Z"));
As per the instructions on this page: https://github./mbostock/d3/wiki/Time-Formatting I am trying to parse an ISO 8601 date for use in D3.js. My test is almost word for word out of the post, I can't get it to work for a full date time string:
var format = d3.time.format("%Y-%m-%d");
alert(format.parse("2011-07-01T19:15:28Z"));
Share
Improve this question
asked Oct 24, 2013 at 21:59
greenafricangreenafrican
2,5465 gold badges29 silver badges39 bronze badges
3 Answers
Reset to default 11You have to add all the fields you're supplying to the format string.
Unlike "natural language" date parsers (including JavaScript's built-in parse), this method is strict: if the specified string does not exactly match the associated format specifier, this method returns null. For example, if the associated format is the full ISO 8601 string "%Y-%m-%dT%H:%M:%SZ", then the string "2011-07-01T19:15:28Z" will be parsed correctly, but "2011-07-01T19:15:28", "2011-07-01 19:15:28" and "2011-07-01" will return null, despite being valid 8601 dates.
Try this:
var format = d3.time.format("%Y-%m-%dT%H:%M:%SZ");
alert(format.parse("2011-07-01T19:15:28Z"));
That creates a new Date object at the time and date specified.
It is super strict, always check your case. eg:
format = d3.time.format("%m/%d/%y");
returns null
but:
format = d3.time.format("%m/%d/%Y");
gives valid results.
For me this issue was caused by me doing the following:
const parseTime = d3.timeParse('%Y-%m-%d');
const pos = parseTime(2021-11-13);
// pos is null but does not error!!
My mistake was giving an equation of integers subtracting from each other as the input which would result in the line ending up as parseTime(1997)
. I needed to make it a string like so:
const pos = parseTime('2021-11-13');
Then pos
is defined properly.