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

蹲街弑〆低调 提交于 2019-12-03 15:08:20

问题


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


回答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.




回答2:


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 :)




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/19346405/jquery-how-to-get-hhmmss-from-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!