Format time using Javascript

I found original version of this function at breakingpar.com. I have slightly changed function to fit my own purpose and purged original article of a really huge amount of completely unnecessary blah-blah, leaving actually Javascript code itself.

Here is my version of the code:

[code language=”javascript”]
function formatTime(timeValue, format)
{
var result = "";
var fmt = format.toUpperCase();
var re = /^(H|HH)(:MM)(:SS)?( AM)?$/;

if(!re.test(fmt)) fmt = "HH:MM:SS";

var MM = "0" + (timeValue.getMinutes());
var SS = "0" + (timeValue.getSeconds());
var H = "" + (timeValue.getHours());
var HH = "0" + H;

MM = MM.substring(MM.length – 2, MM.length);
SS = SS.substring(SS.length – 2, SS.length);
HH = HH.substring(HH.length – 2, HH.length);

if(fmt.indexOf("HH") == -1) result += H + ":" + MM; else result += HH + ":" + MM;
if(fmt.indexOf("SS") != -1) result += ":" + SS;

return result;
}
[/code]

You should call this function like that:

[code language=”javascript”]
var d = new Date();
var n = formatTime(d, ‘HH:MM:SS’);
[/code]

This function only formats time part of Date object. If you need to format in JavaScript whole Date object (both date and time) in the very similar way, as you would do this in PHP, you may consider Date Format 1.2 library presented in Flagrant Badassery blog.

Leave a Reply