Javascript change getHours to 2 digit

Javascript

Javascript Problem Overview


If the hour is less than 10 hours the hours are usually placed in single digit form.

var currentHours = currentTime.getHours ( );

Is the following the only best way to get the hours to display as 09 instead of 9?

if (currentHours < 10)	currentHours = '0'+currentHours;

Javascript Solutions


Solution 1 - Javascript

Your's method is good. Also take a note of it

var date = new Date();
currentHours = date.getHours();
currentHours = ("0" + currentHours).slice(-2);

Solution 2 - Javascript

You can't do much better. Maybe you'll like:

var currentHours = ('0'+currentTime.getHours()).substr(-2);

Solution 3 - Javascript

You can do this using below code,

create function,

function addZeroBefore(n) {
  return (n < 10 ? '0' : '') + n;
}

and then use it as below,

c = addZeroBefore(deg);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionngplaygroundView Question on Stackoverflow
Solution 1 - JavascriptPraveenView Answer on Stackoverflow
Solution 2 - JavascriptPaulView Answer on Stackoverflow
Solution 3 - JavascriptDipesh ParmarView Answer on Stackoverflow