Ognj3n Ognj3n - 4 months ago 7
Javascript Question

Adding one minute to current time in Javascript

I use

Date
object to create time in my
Javascript
code and it should be formated like so :
08:04:21
. This is how I tried to do it:

$('#time').click(function(){
var currentTime = new Date();
var Time=currentTime.getHours() + ":"
+ currentTime.getMinutes() + ":"
+ currentTime.setSeconds(currentTime.getSeconds() + 60);
console.log(Time);
$(this).val(Time);
});


But when
Time
is logged in console string looks like this
8:1:1467844916075
. Same happens when i try this:

var Time=currentTime.getHours() + ":"
+ currentTime.setMinutes(currentTime.getMinutes() + 1) + ":"
+ currentTime.getSeconds();


It bring out similar result : 8:1467844916075:3. I even tried this answer: javascript add one minute to time object

$('#time').click(function(){
var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);
$(this).val(Time);
});


But Time in this case looks like this:
1467785566719
. Any idea how to get human readable current time(not date) plus one minute?

Answer

Please try this,

var currentTime = new Date();
var Time = currentTime.setTime(currentTime.getTime() + 1000 * 60);
console.log(Time);

var date = new Date(Time);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();

// Will display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
Comments