Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get hh:mm:ss from date object? [duplicate]

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,

12:10:1

which should be

12:10:01

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

So I am after this

01:01:01

Not this 1:1:1

like image 587
Run Avatar asked Oct 13 '13 14:10

Run


4 Answers

Solution - (tl;dr version)

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

Explanation:

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.

like image 146
Sunny R Gupta Avatar answered Oct 19 '22 12:10

Sunny R Gupta


I'd suggest you to checkout some date/time library. Moment.js is one good example.

You could do simply as below

var d = new Date();
var formatteddatestr = moment(d).format('hh:mm:ss a');

Here is an example from fiddle

like image 21
Jay Mayu Avatar answered Oct 19 '22 13:10

Jay Mayu


You can use this code snippet. I also added it to jsfiddle and added type-safer comments, so make sure to check out the fiddle.

If you're using jQuery, call it within your ready function. Otherwise you could use plain JavaScript to update the value of your field.

$(document).ready(function(){
    var d = new Date();
    var formatted_time = time_format(d);
    $('#yourTimeField').text(formatted_time);
});

Add these two methods to your script (you could also paste it in a single file, like it is in the jsfiddle code snippet):

function time_format(d) {
    hours = format_two_digits(d.getHours());
    minutes = format_two_digits(d.getMinutes());
    seconds = format_two_digits(d.getSeconds());
    return hours + ":" + minutes + ":" + seconds;
}

function format_two_digits(n) {
    return n < 10 ? '0' + n : n;
}

That's it :) Hope it helps :)

like image 15
Michael Avatar answered Oct 19 '22 12:10

Michael


You can also try using http://momentjs.com/. A javascript date library for parsing, validating, manipulating, and formatting dates.

like image 1
Santosh Avatar answered Oct 19 '22 14:10

Santosh