如何在moment.js中设置日期和时间

问题描述:

momentjs 是否提供任何选项来设置特定时间的时间?

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

var date = "2017-03-13";
var time = "18:00";

var timeAndDate = moment(date).startOf(time);

console.log(timeAndDate);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Moment.js没有提供一种通过字符串设置现有时刻的时间的方法.为什么不将两个连接起来:

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

或者,您可以使用两个Moment对象,也可以使用getter和setter.尽管选项更为冗长,但如果您不能使用串联,则可能会很有用:

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>