guest176969 guest176969 - 3 years ago 161
Javascript Question

JavaScript format current time and twenty minutes later

I am trying to get current time and the time for twenty minutes later in certain format using JavaScript. The desired output should be in this format:

30/09/2017 22:11:23
dd/mm/yyyy hh:MM:ss


Here is my code:

var twentyMinutesLater = new Date,
twentyformat = [
twentyMinutesLater.getDate().padLeft(),
(twentyMinutesLater.getMonth()+1).padLeft(),
twentyMinutesLater.getFullYear()].join('/') +' ' +
[twentyMinutesLater.getHours().padLeft(),
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20).padLeft(),
twentyMinutesLater.getSeconds().padLeft()].join(':');
console.log(twentyformat);

var now = new Date,
nowformat = [
now.getDate().padLeft(),
(now.getMonth()+1).padLeft(),
now.getFullYear()].join('/') +' ' +
[now.getHours().padLeft(),
now.getMinutes().padLeft(),
now.getSeconds().padLeft()].join(':');
console.log(nowformat);

Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}


The output I have obtained:

30/09/2017 22:1506781883422:23
30/09/2017 22:11:23


The twenty minutes later one seemed wrong.

Answer Source

Try this:

var now = new Date();
var in20 = new Date(now.getTime() + (1000*60*20));// add 20 minutes

console.log(now.toLocaleDateString() + " " + now.toLocaleTimeString());
console.log(in20.toLocaleDateString() + " " + in20.toLocaleTimeString());

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download