JavaScript display hour with a zero before it if it is less than 10
When using:
Date.toLocaleTimeString()
is there any way to have it display 01:42:35 PM
instead of 1:42:35 PM
?
I have tried adding in this:
Date.toLocaleTimeString(navigator.language, {hour: '2-digit', minute:'2-digit', second: '2-digit'})
but it still only produces a single digit hour (unless it is after 10).
If my reading is right, according to the relevant spec, it appears this is intentional.
I can't understand why it would be specified that way, but there it is. If you want to do zero-padding, it seems you'll just need to prepend it yourself.
It worked in this way for me
var datelocal = new Date(2016, 01, 01, 1, 1, 1).toLocaleTimeString(navigator.language, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
i'm also attached a plunker.
NOTE : you have to provide new Date() instead of passing date parameters to Date method to get the current date.
Instead of relying on Date.prototype.toLocaleTimeString or similar functions to get the right format in such situations, I tend to use Moment.js in my JavaScript project. Moment.js is a JavaScript library which is specifically designed to parse, validate, manipulate and display dates. To get a string for the time in the format you described, you could use:
var s = moment().format('hh:mm:ss A');
console.log(s);
This uses the current date. If you want to use another date, you can do so, too:
var s = moment(new Date(2016, 8, 19, 1, 10)).format('hh:mm:ss A');
console.log(s);
It saves you the hassle of doing your own zero-padding and other similar stuff.
链接地址: http://www.djcxy.com/p/36054.html