16

Basically, I receive raw timestamps and I need to format them into HH:MM:SS format.

rmk
  • 4,395
  • 3
  • 27
  • 32

3 Answers3

32

Here's a function that provides flexible formatting of a date in UTC. It accepts a format string similar to that of Java's SimpleDateFormat:

function formatDate(date, fmt) {
    function pad(value) {
        return (value.toString().length < 2) ? '0' + value : value;
    }
    return fmt.replace(/%([a-zA-Z])/g, function (_, fmtCode) {
        switch (fmtCode) {
        case 'Y':
            return date.getUTCFullYear();
        case 'M':
            return pad(date.getUTCMonth() + 1);
        case 'd':
            return pad(date.getUTCDate());
        case 'H':
            return pad(date.getUTCHours());
        case 'm':
            return pad(date.getUTCMinutes());
        case 's':
            return pad(date.getUTCSeconds());
        default:
            throw new Error('Unsupported format code: ' + fmtCode);
        }
    });
}

You could use it like this:

formatDate(new Date(timestamp), '%H:%m:%s');
harto
  • 89,823
  • 9
  • 47
  • 61
30

I'll go with the assumption that you mean Unix timestamps:

var formatTime = function(unixTimestamp) {
    var dt = new Date(unixTimestamp * 1000);

    var hours = dt.getHours();
    var minutes = dt.getMinutes();
    var seconds = dt.getSeconds();

    // the above dt.get...() functions return a single digit
    // so I prepend the zero here when needed
    if (hours < 10) 
     hours = '0' + hours;

    if (minutes < 10) 
     minutes = '0' + minutes;

    if (seconds < 10) 
     seconds = '0' + seconds;

    return hours + ":" + minutes + ":" + seconds;
}       

var formattedTime = formatTime(1266272460);
document.write(formattedTime);
JonathanK
  • 3,000
  • 1
  • 20
  • 20
  • 2
    Thanks for the answer, actually I meant Javascript timestamps. javascript timestamp = unix timestamps * 1000 because javascript timestamp is the number of ms since Jan 1 1970 00:00:00 UTC – rmk Feb 23 '10 at 01:17
  • 1
    I modified this for my purposes, which included adding a year, month and day. Two surprises I came across were that you want dt.getDate() instead of dt.getDay() (getDay returns the day of the week); and that dt.getYear() returns what we normally think of as the year (e.g., 2011) in IE 6, but returns the the year - 1900 in the other browsers I tested (Chrome, Opera, Firefox). Just something to be aware of. – Mark Meuer Jul 08 '11 at 20:27
5

This will display the current time in the format you asked for (HH:MM:SS)

function dostuff()
{
 var item = new Date();
 alert(item.toTimeString());
}
Jason Plank
  • 2,336
  • 5
  • 31
  • 40
kaelle
  • 467
  • 2
  • 14
  • 22