How to set time with date in momentjs

后端 未结 5 2018
失恋的感觉
失恋的感觉 2021-02-02 05:19

Does momentjs provide any option to set time with particular time ?

5条回答
  •  清酒与你
    2021-02-02 05:54

    Moment.js does not provide a way to set the time of an existing moment through a string. Why not just concatenate the two:

    var date = "2017-03-13";
    var time = "18:00";
    
    var timeAndDate = moment(date + ' ' + time);
    
    console.log(timeAndDate);

    Alternatively, you can use two Moment objects and use the getters and setters. Although a far more verbose option, it could be useful if you can't use concatenation:

    let dateStr = '2017-03-13',
        timeStr = '18:00',
        date    = moment(dateStr),
        time    = moment(timeStr, 'HH:mm');
    
    date.set({
        hour:   time.get('hour'),
        minute: time.get('minute'),
        second: time.get('second')
    });
    
    console.log(date);

提交回复
热议问题