Convert time to seconds in javascript

//Convert time to seconds in javascript

In my projects I often have to reuse the same code over and over again. When it comes to back end programming I have lots of libraries ready, which I simply reference to my projects and save time and frustration of having to write the same code. But when it comes to javascript development, I didn’t have the need so far to concentrate into a single location some useful functions and methods that I often use. Some of these methods are time related and converting it to seconds, milliseconds and vice versa converting seconds, and milliseconds back to time.

After all why use frameworks and affect the performance of your project when you can do something yourself.

Below you will find the following prototypes

  • convert seconds to time
  • convert milliseconds to time
  • convert time to seconds
  • convert time to milliseconds
String.prototype.secondsToHHMMSS = function () {
    
	var s= parseInt(this, 10); // Second Param is for decimal see http://www.w3schools.com/jsref/jsref_parseint.asp 
	return s.secondsToHHMMSS();
}

Number.prototype.secondsToHHMMSS = function () {
    var h   = Math.floor(this / 3600);
    var m = Math.floor((this - (h * 3600)) / 60);
    var s = this - (h * 3600) - (m * 60);

    if (h   < 10) {h   = "0"+h;}
    if (m < 10) {m = "0"+m;}
    if (s < 10) {s = "0"+s;}
    return h+':'+m+':'+s;
}

String.prototype.millisecondsToHHMMSS = function () {
	var m = parseInt(this, 10); // Second Param is for decimal see http://www.w3schools.com/jsref/jsref_parseint.asp 
	return m.millisecondsToHHMMSS();
}

Number.prototype.millisecondsToHHMMSS = function () {
	var s = this / 1000; 
	return s.secondsToHHMMSS();
}


String.prototype.HHMMSSToSeconds = function () {
	var hms = this.split(/[.:]/);
	/*var h = parseInt(hms[0], 10);
	var m = hoursMinutesSeconds[1] ? parseInt(hms[1], 10) : 0;
	var s = hms[2] ? parseInt(hms[2], 10) : 0;*/
  
	return ((+hms[0] * 3600) + (+hms[1] * 60) + (+hms[2]));
}

String.prototype.HHMMSSToMilliseconds = function () {
	return this.HHMMSSToSeconds() * 1000;
}

Usage for time to Seconds javascript

<div id="foo"></div>
document.getElementById("foo").innerHTML = "12:36:52".HHMMSSToSeconds();

Usage for time to Milliseconds javascript

<div id="foo"></div>
document.getElementById("foo").innerHTML = "12:36:52".HHMMSSToMilliseconds();

Usage for seconds to time javascript

<div id="foo"></div>
document.getElementById("foo").innerHTML = "12:36:52".secondsToHHMMSS();

Do you have any methods you find useful and you would like to share?

2017-03-05T13:51:28+00:00 January 9th, 2017|javascript|0 Comments

Leave A Comment