teelou teelou - 1 year ago 116
Javascript Question

jquery: How to get hh:mm:ss from date object?

How can I get this hh:mm:ss from date object?

var d = new Date(); // for now
datetext = d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();

I get this result below sometimes,


which should be


I assume this happens to the hour and minute as well.

So I am after this


Not this 1:1:1

Answer Source

Solution - (tl;dr version)

datetext = d.toTimeString().split(' ')[0]


toTimeString returns the complete time. We split it by space to get the time component only, then take the first value which is of use. :)

Complete Flow:

d = new Date();
// d is "Sun Oct 13 2013 20:32:01 GMT+0530 (India Standard Time)"
datetext = d.toTimeString();
// datestring is "20:32:01 GMT+0530 (India Standard Time)"
// Split with ' ' and we get: ["20:32:01", "GMT+0530", "(India", "Standard", "Time)"]
// Take the first value from array :)
datetext = datetext.split(' ')[0];

Note: This does not require you to include any external files or libraries hence time required for execution would be faster.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download