Home > Net >  Convert utc time string to date object
Convert utc time string to date object

Time:06-23

I have time string as below:

2022-06-20T19:00:00.1620000Z

I try below code to convert it to datetime object but it return null

var t1 = d3.timeParse("%Y-%m-%d %H:%M:%S.%LZ")("2022-06-20T19:00:00.1620000Z")
console.log("debug:",t1)

CodePudding user response:

First of all, mind the T between the day and the hour.

The issue here is that you're using %L, which accepts milliseconds (from 000 to 999), when you should be using %f for microseconds. But even if you use %f you have a problem: your string has seven decimal places for seconds, and %f accepts only six. Therefore, you have to trim that string, using whatever method you like.

For instance (look at your browser's console, not the snippet console):

let t = "2022-06-20T19:00:00.1620000Z";
t = t.slice(0, -2)   t.slice(-1);
const t1 = d3.timeParse("%Y-%m-%dT%H:%M:%S.%fZ")(t)
console.log("debug:",t1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.4.0/d3.min.js"></script>

  • Related