Reputation: 1751
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
Upvotes: 2
Views: 2716
Reputation: 1
You can write your own function for this.
My case is not exactly same with your case. But you can slightly modify the microsecond extraction part then it will solve the case.
For my case I wanted to convert this date time string
"2025-02-20 11:52:49.797296"
to
"1740052369797296"
in javascript
I used following function
function convertToMicroseconds(datetimeString) {
// Split date and microseconds
const [datePart, microsecondPart] = datetimeString.split('.');
// Convert date part to a timestamp (milliseconds)
const date = new Date(datePart);
const milliseconds = date.getTime(); // Get milliseconds since Unix epoch
// Ensure microsecondPart is exactly 6 digits
const microseconds = microsecondPart.padEnd(6, '0');
// Concatenate milliseconds (convert to seconds first) and microseconds
return BigInt(milliseconds) * 1000n + BigInt(microseconds);
}
Upvotes: 0
Reputation: 102208
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:
"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>
"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";✻ Title edited.
Upvotes: 3
Reputation: 527
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");
Upvotes: -1