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 <
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')
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 so7.23:59:59
. Partial seconds are supported as well23: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>
Try using
moment.add(5,'hours').add(30,'minutes').format('HH:mm')
OR
moment().add({hours:5, minutes: 30}).format('HH:mm')
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);
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');