Add hours minutes with the format hh:mm using moment

前端 未结 5 376
自闭症患者
自闭症患者 2021-01-21 00:55

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 <

相关标签:
5条回答
  • 2021-01-21 01:27

    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')
    
    0 讨论(0)
  • 2021-01-21 01:31

    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>

    0 讨论(0)
  • 2021-01-21 01:33

    Try using

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

    OR

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

    0 讨论(0)
  • 2021-01-21 01:37

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

    0 讨论(0)
  • 2021-01-21 01:39
    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');
    
    0 讨论(0)
提交回复
热议问题