0

How to get hours when hour is < 10 append "0" to hour?

For Exemple:

javascript{new Date().getHours() +":" + new Date().getMinutes())} Result: 9:20...

I need to format "09:20".

albciff
  • 16,966
  • 4
  • 58
  • 79

2 Answers2

0
var d = new Date();

console.log(
    (d.getHours() < 10 ? '0' : '') + d.getHours() + ':' +
    (d.getMinutes() < 10 ? '0' : '') + d.getMinutes()
);

-- you can test that in a browser & node.js console.

Or, in your syntax, I guess:

javascript{
    d = new Date(),
    (d.getHours() < 10 ? '0' : '') + d.getHours() + ':' +
    (d.getMinutes() < 10 ? '0' : '') + d.getMinutes()
}
Ivan Krechetov
  • 17,548
  • 8
  • 45
  • 58
0

please find below a clean solution that uses the common format tool

today = new Date();
var dateString = today.format("dd:mm");
alert(dateString);

For more details and a jsfiddle , please look here

Community
  • 1
  • 1
  • I don't think Date.prototype.format() exists http://screencast.com/t/6hO9NZVSaRc See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype – Ivan Krechetov Sep 04 '14 at 13:25
  • you are right Ivan, you have to add the prototype referenced in the jsFiddle.I must admit that ,if it is just for one formating operation , your solution is lighter and better.But in case you need to make more date manipulations , the prototype is broader. – Yannick Serra Sep 04 '14 at 13:39