I have this ISO 8061 2017-05-03T06:31:46.687123+00:00
which I want to convert it to YYYY-MM-DD
using D3. Any help will be appreciated.
Asked
Active
Viewed 622 times
1

Prajwal
- 321
- 2
- 4
- 21
-
Possible duplicate of [Where can I find documentation on formatting a date in JavaScript?](https://stackoverflow.com/questions/1056728/where-can-i-find-documentation-on-formatting-a-date-in-javascript) – edcs Jun 15 '17 at 08:04
-
Since your question is on how to do it with `d3.js` I would include it in the title for the other users that will see it in the future. – tgogos Jun 15 '17 at 08:55
-
@tgogos No, including tags into the tilte is frowned upon on SO: https://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles. – altocumulus Jun 16 '17 at 11:26
-
@altocumulus thanks, good to know that. My thought was that it would be useful to read something like "How to convert ISO 8061 to YYYY/MM/DD with d3.js? when you are navigating in SO. – tgogos Jun 16 '17 at 11:29
4 Answers
2
check out momentjs and specifically the format function: https://momentjs.com/docs/#/displaying/
You can then write something like:
moment("2017-05-03T06:31:46.687123+00:00").format("YYYY-MM-DD");

MattjeS
- 1,367
- 18
- 35
2
Since you want to use d3.js
... be careful with the version you are using because there has been a small change to the name of the function:
- with v.3.4.11 use
d3.time.format("%Y-%m-%d")
- with v.4.9.1 use
d3.timeFormat("%Y-%m-%d")
3.4.11
your_date = new Date('2017-05-03T06:31:46.687123+00:00')
var formatTime = d3.time.format("%Y-%m-%d");
new_date = formatTime( your_date ); // 2017-05-03
console.log(new_date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
4.9.1
your_date = new Date('2017-05-03T06:31:46.687123+00:00')
var formatTime = d3.timeFormat("%Y-%m-%d");
new_date = formatTime( your_date ); // 2017-05-03
console.log(new_date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.9.1/d3.min.js"></script>

tgogos
- 23,218
- 20
- 96
- 128
0
i think this code will work but i didnt test it yet can you test it and give me a feedback please
date = new Date('2017-05-03T06:31:46.687123+00:00');
year = date.getFullYear();
month = date.getMonth() + 1;
dt = date.getDate();
if (dt < 10) {
dt = '0' + dt;
}
if (month < 10) {
month = '0' + month;
}
console.log(year + '-' + month + '-' + dt);
you can also crop the date
dat.toISOString().substring(0, 10)

tgogos
- 23,218
- 20
- 96
- 128
-
1You can use the `html / css / js snippet` icon where you can add / test your code directly – tgogos Jun 15 '17 at 09:02
0
When I found this library - https://date-fns.org/ I prefer it instead of moment.js. Date-fns is modular, and your could import only one method. This allows significantly reduced bundle size in compare with not modular moment.js:
import format from 'date-fns/format';
format('2017-05-03T06:31:46.687123+00:00', 'YYYY-MM-DD');

Mikhail Shabrikov
- 8,453
- 1
- 28
- 35