I am trying to parse a timestamp to use in a plot in d3.js
but I cannot manage to get it to work. Examples of the timestamp are shown below:
- 2022-02-17 09:52:37.000000
- 2022-02-17 09:54:00.000000
The code that I use to do the parsing is:
`const dateParser = d3.timeFormat("%Y-%m-%d");
data.forEach(function(d) {
d.timestamp = dateParser(d.ts);
});`
Where d.ts
is the timestamp
The output I get at the moment is under the form:
0NaN-NaN-NaN
Thanks in advance
CodePudding user response:
In a way, parsing is the opposite of formatting: when you parse you convert a string to a date, while formatting is converting the date to a readable string (also, pay attention to your specifier, it's incorrect).
Therefore, you want d3.timeParse()
instead. Here is the working snippet, look at your browser's console, not the snippet's one:
const dates = ["2022-02-17 09:52:37",
"2022-02-17 09:54:00"
];
const dateParser = d3.timeParse("%Y-%m-%d %H:%M:%S");
dates.forEach(function(d) {
console.log(dateParser(d));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
CodePudding user response:
Are your dates strings? If so you could change your code to first convert the string date to Date object and then call dateParser on it:
data.forEach(function(d) {
d.timestamp = dateParser(new Date(d.ts));
});