问题
I have some datetime string e.g.
"2017-10-29T02:54:03.125983+00:00"
"2017-10-29T02:09:22.1453833+00:00"
with 6 or 7 digital length milliseconds, how can I parse it to date object in d3 javascript language? I have tried
d3.timeParse("%Y-%m-%dT%H:%M:%S.%LZ");
but failed, it returns null
回答1:
What you have is not a long millisecond✻: that is a microsecond.
There is a specifier in D3 for microseconds since D3 v4 (see here). To parse microseconds, use "f". According to the API:
%f - microseconds as a decimal number [000000, 999999].
Here is a demo with your string (don't look at the Stack snippet console, click "Run code snippet" and open your browser console to see the actual date):
var date = "2017-10-29T02:54:03.125983+00:00";
var parser = d3.timeParse("%Y-%m-%dT%H:%M:%S.%f%Z");
console.log(parser(date))
<script src="https://d3js.org/d3-time-format.v2.min.js"></script>
Three observations:
- Contrary to what the own API says,
"f"will not work with the default bundle. You have to reference the standalone time microlibrary (have a look at my demo above to see the URL). Lets prove it:
var date = "2017-10-29T02:09:22.145383+00:00";
var parser = d3.timeParse("%Y-%m-%dT%H:%M:%S.%f%Z");
console.log(parser(date))
<script src="https://d3js.org/d3.v4.min.js"></script>
- Remove that
"Z". It should be"%Z"instead. As the API says, "Note that the literal Z here is different from the time zone offset directive %Z"; - There is no microsecond with 7 digits. It has to be 6 digits.
✻ Title edited.
回答2:
You are trying to parse a date object which is incorrect, I think you want to format the date object.
Instead of:
d3.timeParse("%Y-%m-%dT%H:%M:%S.%LZ");
try this:
d3.timeFormat("%Y-%m-%dT%H:%M:%S.%LZ");
来源:https://stackoverflow.com/questions/47008978/how-to-parse-a-date-string-with-microseconds