Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript change getHours to 2 digit [duplicate]

Tags:

javascript

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; 
like image 253
ngplayground Avatar asked Sep 19 '13 08:09

ngplayground


People also ask

How to get time in 2 digit in JavaScript?

To change the getMinutes() method to 2 digit format:Use the getMinutes() method to get the minutes. Use the padStart() method to add a leading zero if it's necessary. The padStart method allows us to add a leading zero to the start of the string.


2 Answers

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

var date = new Date(); currentHours = date.getHours(); currentHours = ("0" + currentHours).slice(-2); 
like image 185
Praveen Avatar answered Oct 04 '22 04:10

Praveen


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); 
like image 42
Dipesh Parmar Avatar answered Oct 04 '22 05:10

Dipesh Parmar