'Why .getMinutes() output as :0 instead of :00 in JavaScript?

The .getMinutes() method only outputs one integer ‘0’ instead of two integers ‘00’. Why does it do this and is there a simpler way to fix this?

Example:

        var dateDue = new Date("Fri Apr 22 2022 18:00:00");
        dateDue.getMinutes();   //Expected output: 18:00, got 18:0 instead?

For now I have been using if statement validation to add 0 whenever the minutes .Length returns as only being one character long instead of two.

        //Minutes display validation for dateDue
        var minutesDue = dateDue.getMinutes();
        if (minutesDue.Length === 1) {
        minutesDue = parseInt(dateDue.getMinutes()) + "0";

Coding language: JavaScript (vanilla)
Skill level: Beginner
Editor: Visual Studio Code
OS: Windows 7



Solution 1:[1]

You can use the toLocaleTimeString method with some options for padding and even more styling. This one does AM/PM automatically for you.

const time = new Date("Fri Apr 22 2022 18:00:00").toLocaleTimeString('default', { hour: '2-digit', minute: '2-digit' });
console.log(time) // '06:00 PM'

Solution 2:[2]

I could answer half the question if it helps to start thinking process. To put :00 for seconds. You need a loop which checks the condition, if seconds less than 9. If that's the case concatenate 0 to secs.

Solution 3:[3]

var dateDue = new Date("Fri Apr 22 2022 18:00:00");
if (dateDue.getMinutes() < 10) {
       var getMinutes= '0' + dateDue.getMinutes();
   }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Palm
Solution 2 Kamran qureshi
Solution 3 Vishwa