Ansjovis86
Ansjovis86

Reputation: 1545

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

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?

Upvotes: 4

Views: 22949

Answers (2)

Blagoje Stankovic
Blagoje Stankovic

Reputation: 148

You can use IF condition to see if minutes < 10

to add "0" like 07,08

var d = new Date() var n = d.getMinutes() if(n<10) n="0"+n;

But watch out you will have to slice that zero if you want to increment.

EDIT: I was young when wrote this. A better approach is: moment(YOUR_DATE).format('HH:mm')

Upvotes: -6

VincenzoC
VincenzoC

Reputation: 31482

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

Upvotes: 14

Related Questions