Formatting the Date and Time

Learn about the date and time formats used in D3.

Why we need different formats

One of the glorious things about the world is that we all do things a bit differently. One of those things is how we refer to dates and time.

In my neck of the woods, it’s customary to write the date as day - month – year, e.g., 23-12-2012. But in the United States, the more common format would be 12-23-2012. Likewise, the data may be in formats that name the months or weekdays (e.g., January and Tuesday) or combine dates and time together (e.g., 2012-12-23 15:45:32). So if we were to attempt to load in some data and try to get D3 to recognize it as date/time information, we really need to tell it what format the date/time is in.

You might be asking yourself: “What’s the point?” All we want to do is give it a number, and it can sort it out somehow. Well, that is true, but if we want to really bring out the best in our data and keep maximum flexibility in representing it on the screen, we will want D3 to play to its strengths. And one of those is being able to adjust dynamically with variable time values.

Changing the data

We will change our data.csv file so that it only includes two points: the first one and the last one with a separation of a month and a bit.

It will, therefore, look a little like this:

date,close 
1-May-12,58.13 
26-Mar-12,606.98

The graph now looks like this:

Get hands-on with 1200+ tech skills courses.