最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - D3 time parse returns null - Stack Overflow

programmeradmin5浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 11

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

发布评论

评论列表(0)

  1. 暂无评论