如何在moment.js中设置日期和时间 [英] How to set time with date in momentjs

查看:2136
本文介绍了如何在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>

这篇关于如何在moment.js中设置日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆