Skip to content Skip to sidebar Skip to footer

Add Hours Minutes With The Format Hh:mm Using Moment

I am using moment library and from front end I am getting time in HH:mm I need to add hours and minutes to current time using moment. Suppose I am getting 05:30 from the frontend a

Solution 1:

You can create a duration for '05:30' using moment.duration(String) and the use add(Duration).

As moment duration docs states, '05:30' is a valid input for moment.duration(String):

As of 2.1.0, moment supports parsing ASP.NET style time spans. The following formats are supported.

The format is an hour, minute, second string separated by colons like 23:59:59. The number of days can be prefixed with a dot separator like so 7.23:59:59. Partial seconds are supported as well 23:59:59.999.

Here a live sample:

const result = moment().add( moment.duration('05:30') );
console.log( moment().format() );
console.log( result.format() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Solution 2:

EDIT: @VincenzoC above provided what I personally think is the best practice. Check this answer only as an alternative to his.

Just do:

moment().add({
   hours: 5,
   minutes: 30
});

As suggested in the official documentation: http://momentjs.com/docs/#/manipulating/add/

Either use the object literal as above, or use chaining.

I you can't get rid of that string, just acquire hours and minutes by splitting:

let [hours, minutes] = '05:30'.split(':').map(Number);
console.log(hours);
console.log(minutes);

Solution 3:

Moment have .add property

moment().add(1, 'day')

Reference: http://momentjs.com/docs/#/manipulating/add/

For converting to specific format:

moment().add({hours:5, minutes: 30}).format('HH:mm')

Solution 4:

var t = '05:30';
var hours = parseInt(t.substr(0,2));
var minutes = parseInt(t.substr(3,5));
moment().add(hours,'hours').add(minutes,'minutes');

Solution 5:

Try using

moment.add(5,'hours').add(30,'minutes').format('HH:mm')

OR

moment().add({hours:5, minutes: 30}).format('HH:mm')


Post a Comment for "Add Hours Minutes With The Format Hh:mm Using Moment"