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
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.
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
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 :)
You can also try using http://momentjs.com/. A javascript date library for parsing, validating, manipulating, and formatting dates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With