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!

1
  • 1
    why don't you format as var completeD = start.format("HH:mm"); go thought it? Commented Feb 9, 2016 at 13:45

4 Answers 4

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()));
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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) ; 

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.