JavaScript epoch time converter number method

Jan 09, 2010

Overview

The code below extends the JavaScript Number object with a method that will convert an epoch time into a string that represents the days, hours, minutes and seconds of the given epoch number. For example, the method will turn the number “98635″ into the string “1 days, 3 hours, 23 minutes, 55 seconds”.

I made this simple number object method one day for a side project of mine where I needed to profile the amount of time that certain ajax calls were taking to complete. I then average these times together and after multiplied that average by the number of requests that were still left to complete. This provided me with an estimated time of completion for x number of ajax calls. To get the difference of the time, I just created a new date when the ajax call started and another after it finished. Since JavaScript stores these times as seconds since the epoch, it’s easy to subtract one from the other to get the amount of time it took for the ajax call to complete. As soon as I had the number of milliseconds that all the remaining ajax calls would take to complete (according to my average calculation), I used this method to return something readable to a human being. I hope you find it useful.

Usage

To use the method, simply create a number type variable (var time = 98635;) and then call the method named ‘timeLeft’ on the variable, like so: “var timeLeft = time.timeLeft();”.

The Code

Minified Code:

Full Code: