0

I have this code:

CODE JS:

var completeD = start.format("YYYY/MM/DD HH:mm");
var dt = new Date(completeD);
console.log(dt)   //here it's display Tue Feb 09 2016 02:00:00 GMT+0200 (EET)  
console.log(dt.getHours() + ":" + dt.getMinutes()); //the input value is 2:0

The input value is 2:0 and should be 02:00

How can I add a 0 in front ...?if it's neccesarry.

Thanks in advance!

Marius
  • 1,181
  • 3
  • 15
  • 23

4 Answers4

1

simple way is to write a function to correct the string:

function normalize(n) {
    if (n < 10) {
        n = "0" + n;
    }
    return n;
} 
var completeD = start.format("YYYY/MM/DD HH:mm");
var dt = new Date(completeD);
console.log(normalize(dt.getHours()) + ":" + normalize(dt.getMinutes()));
Taran J
  • 805
  • 6
  • 10
0

use a pad function

function pad(var value) {
    if(value < 10) {
        return '0' + value;
    } else {
        return value;
    }
}

now you can use it

 console.log( pad( dt.getHours() ) + ":" + pad ( dt.getMinutes()) ); // outputs 02:00
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

You can try this : (click on run code snippet to see result in console)

  
var dt = new Date();
console.log(dt)   //here it's display Tue Feb 09 2016 02:00:00 GMT+0200 (EET) 
var hours = dt.getHours();
var minute = dt.getMinutes();
  
if(hours.toString().length == 1 ) hours = "0"+hours;
if(minute.toString().length == 1 ) minute = "0"+minute;
console.log(hours + ":" + minute); //the input value is 2:0
alert(hours + ":" + minute) ; 
Bourbia Brahim
  • 14,459
  • 4
  • 39
  • 52
0

You can use regular expression for it:

var dt = 'Tue Feb 09 2016 02:00:00 GMT+0530 (India Standard Time)';//new Date();
document.querySelector('pre').innerHTML = dt.match(/(\d\d:\d\d)/g)[0];
<pre></pre>
Jai
  • 74,255
  • 12
  • 74
  • 103