63

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;
ngplayground
  • 20,365
  • 36
  • 94
  • 173
  • Better ways are: 1) use [moment.js](http://momentjs.com/) and its formatting abilities, 2) use a generic formatting function, e.g. http://stackoverflow.com/q/610406/989121 – georg Sep 19 '13 at 08:34
  • 7
    With EcmaScript 6: ```new Date().getHours().toString().padStart(2, '0');``` – Manz Nov 16 '18 at 09:46

3 Answers3

173

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

var date = new Date();
currentHours = date.getHours();
currentHours = ("0" + currentHours).slice(-2);
Reporter
  • 3,897
  • 5
  • 33
  • 47
Praveen
  • 55,303
  • 33
  • 133
  • 164
17

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

var currentHours = ('0'+currentTime.getHours()).substr(-2);
Paul
  • 139,544
  • 27
  • 275
  • 264
  • This is amazing. I have created a custom function based on this. `get_current_date_time() { var today = new Date(); var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); var currentHours = ('0'+today.getHours()).substr(-2); var currentMins = ('0'+today.getMinutes()).substr(-2); var currentSecs = ('0'+today.getSeconds()).substr(-2); var time = currentHours + ":" + currentMins + ":" + currentSecs; var dateTime = date + ' ' + time; return dateTime; }` – The Sammie Oct 26 '17 at 21:35
  • `substr()` is deprecated, but you can use `slice()` to do the same thing (using a negative number to count from the end). – Abel Wenning Mar 31 '22 at 08:35
15

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);
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
  • 1
    I like this approach: simple, elegant. Here's how I use it to format time: `code -- function nn(n) { return (n < 10 ? '0' : '') + n; } function getTime(){ var now = new Date();
    var h = nn(now.getHours()); var m = nn(now.getMinutes()); var s = nn(now.getSeconds()); return [ h, m, s ].join(':'); }`
    – Marty McGee Jun 06 '15 at 16:22