hktang
hktang

Reputation: 1833

What is a good way to convert %H:%M:%S strings to timespan?

I have a data set with most of the data points in H:M:S format, such as 20:59:59, showing the time span used by individual athletes at different laps.

With D3.js, what is the best way to convert it to time spans, i.e. number of seconds?

I tried parser = d3.timeParse("%H:%M:%S"); but it seems to be very wrong..

Upvotes: 1

Views: 597

Answers (2)

harmic
harmic

Reputation: 30597

If you are using D3 3.x, then you can construct a suitable parser with:

var parser=d3.time.format("%H:%M:%S");

or if you were using D3 4.x:

var parser=d3.timeParse("%H:%M:%S");

Either way, you would then be able to convert your data points into JS Date objects like this:

var t1 = parser.parse("20:59:59");
var t2 = parser.parse("21:02:13");

You can find out the elapsed time between these two time instances by subtracting, eg:

var elapsed = t2 - t1; /* Returns 134000 = 134 seconds */

elapsed will be the number of elapsed milliseconds.

The reason that works is that Date objects provide a valueOf() method which returns the number of milliseconds elapsed since Jan 1 1970. Subtracting the date objects automatically calls valueOf() and subtracts the returned values.

Note that if the time strings you are parsing do not include a date portion, then you will have problems if the starting time and ending time are not in the same day.

EDIT:

From the comments it becomes clear that the times you are working with are already lap durations, in H:M:S format, and you want to convert them to seconds. That does not require D3, it is easy enough:

var components = /^(\d+):(\d+):(\d+)$/.exec("20:59:59");
var elapsedSecs = components[1]*3600+components[2]*60+components[3];

Upvotes: 3

sparta93
sparta93

Reputation: 3854

You can use d3.time.format("%H:%M:%S") for your conversion.

Upvotes: 0

Related Questions