最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add hours minutes with the format hh:mm using moment - Stack Overflow

programmeradmin3浏览0评论

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 and I need to add to the current UTC time. How can I do that using momentjs?

I tried that but didn't work

moment().add('05:30', 'HH:mm')

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 and I need to add to the current UTC time. How can I do that using momentjs?

I tried that but didn't work

moment().add('05:30', 'HH:mm')
Share Improve this question asked May 9, 2019 at 8:03 ProferProfer 64310 gold badges47 silver badges96 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 12

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>

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);

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')
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');

Try using

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

OR

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

发布评论

评论列表(0)

  1. 暂无评论