Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add minutes in moment js with a HH:mm format?

Tags:

momentjs

How do I add minutes to this. I followed the documentation but somehow this is not working:

var hours = randomIntFromInterval(0,23);
var minutes = randomIntFromInterval(0,59);
var time = moment(hours+':'+minutes,'HHmm').format("HH:mm");
time.add(7,'m');

Only the last line is not working, but should be right according to the documentation. What am I doing wrong?

like image 539
Ansjovis86 Avatar asked Apr 18 '17 14:04

Ansjovis86


People also ask

How do I change moment format time?

Try: moment({ // Options here }). format('HHmm') . That should give you the time in a 24 hour format.


1 Answers

format returns a string, you have to use add on moment object.

Your code could be like the following:

var hours = randomIntFromInterval(0,23);
var minutes = randomIntFromInterval(0,59);
var time = moment(hours+':'+minutes,'HH:mm');
time.add(7,'m');
console.log(time.format("HH:mm"));

Note that you can create a moment object using moment(Object) method instead of parsing a string, in your case:

moment({hours: hours, minutes: minutes});

As the docs says:

Omitted units default to 0 or the current date, month, and year

like image 192
VincenzoC Avatar answered Nov 10 '22 14:11

VincenzoC