Not Rocket Science

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();
ts.AddHours(3);
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.

Example:

// 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.

Post Tags
My Software