Reputation: 833
I'm pretty sure this is simple but I am trying to print out the current time in 12-hour format without including the leading zero in the time string. So, for example.
09:30 AM should print as 9:30 AM.
The current code I have so far (which prints the version with the leading zero) is this:
var d = new Date();
var timeString = d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
How can I change the above code to remove the leading zeros when they appear?
Upvotes: 2
Views: 696
Reputation: 4194
Use the numeric
format for the hour instead of 2-digit
var timeString = d.toLocaleTimeString([], {hour: 'numeric', minute:'2-digit'});
const d = new Date();
d.setHours(9, 30);
console.log(d.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'}));
console.log(d.toLocaleTimeString([], {hour: 'numeric', minute:'2-digit'}));
Upvotes: 3
Reputation: 163602
Your code is specifying:
hour: '2-digit'
Just get rid of that and all is well. :-)
For the US locale, here's what I get:
const d = new Date();
console.log(
d.toLocaleTimeString() // 8:40:28 PM
);
Upvotes: 1