Home > Software engineering >  Printing Time without leading zero in Javascript
Printing Time without leading zero in Javascript

Time:12-27

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?

CodePudding user response:

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

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString#using_options

CodePudding user response:

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'}));

  • Related