Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 349
rjbogz Avatar asked Aug 26 '16 17:08

rjbogz


People also ask

How do you put a zero in front of a number in TypeScript?

To add leading zeros to a number in TypeScript:Convert the number to a string. Call the padStart() method to add zeros to the start of the string. The padStart method returns a new string with the specified pad string applied from the start.

How do I pad a number in JavaScript?

padStart() The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.

How to format Date time in js?

The string format should be: YYYY-MM-DDTHH:mm:ss. sssZ , where: YYYY-MM-DD – is the date: year-month-day. The character "T" is used as the delimiter.


1 Answers

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.

like image 120
DigitalDNA Avatar answered Nov 07 '22 19:11

DigitalDNA