JavaScript TimeSpan Library

Working with Time is always weird. Some functions want milliseconds, others want seconds. And if you want to express "3 hours" in milliseconds, usually the result looks like var targetTime = 3 * 60 * 60 * 1000; which is a bit ugly in my opinion. Also, I always have to remember what to actually add together 🙂

As a .net Developer, I'm used to the useful System.TimeSpan and System.DateTime structs which have such useful features like AddHours or TotalMilliseconds to have a more natural way to work with Time.

I wrote a JavaScript library that mixes useful functionality from these two structs into "class". Here is a quick example:

var ts = new TimeSpan();
alert(ts.TotalMilliseconds()); // Outputs 10800000

// There are also "static constructors":
var ts = TimeSpan.FromHours(3);
alert(ts.TotalMilliseconds()); // Outputs 10800000

There are also functions to Add/Subtract another TimeSpan and an Equals function to compare two TimeSpans. Note that there are two types of getters. There are the TotalSeconds/Hours/etc. functions that return a floating point number. And then there are the Seconds/Hours/etc. functions that return an Integer, but that only return a fraction of the TimeSpan that can be used to create a clock. This mirrors the behavior of the .net TimeSpan.


// TimeSpan for 3 Days, 2 Hours, 10 Minutes and 4 Seconds
var ts1 = new TimeSpan(0, 4, 10, 2, 3);
alert(ts1.TotalDays()); // 3.0903240740740743
alert(ts1.TotalHours()); // 74.16777777777777
alert(ts1.Hours()); // 2, not 74.
alert(ts1.Days()); // 3

I haven't written Documentation or VSDoc comments yet, and there is no minified version either, but in the next days I'll add them. In the meantime, Download it from GitHub. It is licensed under MIT license.

Comments (5)

sMarch 3rd, 2010 at 10:09

Fine lib, but missing some important things. Like creating Timespan from two dates and working on that like:
var ts = new TimeSpan(destinationDate, currentDate);

mstumMarch 4th, 2010 at 07:50

Thanks, written that down for the next version.

mstumMarch 5th, 2010 at 08:45

Version 1.2 can create a TimeSpan from two dates, using TimeSpan.FromDates

LoniDecember 14th, 2010 at 23:06

Thank you so much for this. As a VB.NET developer, I was really scratching my head trying to replicate this much-beloved functionality in JavaScript!

MerlynApril 14th, 2012 at 00:15

I know .Net uses initial caps in method/property names, but Javascript doesn't follow that convention. Also .Net properties hide the get_ set_ names of the getter and setter methods, and the parens, but Javascript doesn't. You should make the method/property names initial lowercase, and name getters/setters "getSomething"/"setSomething":

var ts = new TimeSpan();

var ts = TimeSpan.fromHours(3);

var ts1 = new TimeSpan(0, 4, 10, 2, 3);