Reputation: 3303
I'm having trouble understanding how d3.timeParse
works. I initialize the function at the beginning like this:
var dateParse = d3.timeParse("%Y-%m-%d");
I then call it here:
d3.json("data3.json", function(error, data) {
//populating data since i don't have the file
data = [{
"date": "2017-01-04",
"open": 10430.69
}, {
"date": "2017-01-05",
"open": 10584.56
}];
data.forEach(function(d) {
d.dd = dateParse(d.date);
console.log(d.dd);
});
The problem is that console.log(d.dd);
returns the following string
Wed Jan 04 2017 00:00:00 GMT-0400 (SA Western Standard Time)
when it should return this:
2017-01-04
I've tried changing the format of the parameter (if that's what this really is) from "%Y-%m-%d"
to anything else, but any change returns null.
Any help is appreciated.
Thanks.
Upvotes: 1
Views: 1366
Reputation: 8509
Use timeFormat
, and wrap d.date
to new Date(d.date)
:
var dateParse = d3.timeFormat("%Y-%m-%d");
var data = [{
"date": "2017-01-04",
"open": 10430.69
}, {
"date": "2017-01-05",
"open": 10584.56
}];
data.forEach(function(d) {
d.dd = dateParse(new Date(d.date));
console.log(d.dd);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>
Upvotes: 2
Reputation:
You can also use moment.js library and all your date-related operations can become very easy. https://momentjs.com/
If you have the library you can try this
data.forEach(function(d) {
d.dd = moment(d["date"], "YYYY-MM-DD");;
console.log(d.dd);
});
Upvotes: 1