Javascript 如何在momentjs中设置带有日期的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42515588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:12:54  来源:igfitidea点击:

How to set time with date in momentjs

javascriptdatedatetimetimemomentjs

提问by Mo.

Does momentjsprovide any option to set time with particular time ?

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

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>

enter image description here

在此处输入图片说明

回答by BenM

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

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

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>

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:

或者,您可以使用两个 Moment 对象并使用 getter 和 setter。虽然这是一个更加冗长的选项,但如果您不能使用连接,它可能会很有用:

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>

回答by LoKat

Since this pops up in google results, moment now has a set(unit, value)function and you can achieve this by:

由于这会在 google 结果中弹出,因此 moment 现在有一个set(unit, value)功能,您可以通过以下方式实现:

const hours = 15;
const minutes = 32;
var date = moment("1946-05-21").set("hour", hours).set("minute", minutes);

or as a combined function

或作为组合功能

var date = moment("1946-05-21").set({"hour": 15, "minute": 32});

Note: the setfunction requires the value to be Integer type

注意:set函数要求值为Integer类型

回答by Ben Winding

Just incase anyone is wondering how to set the time on a Date Object, here's how I did it:

以防万一有人想知道如何在Date Object上设置时间,我是这样做的:

const dateObj = new Date();

const dateStr = dateObj.toISOString().split('T').shift();
const timeStr = '03:45';

const timeAndDate = moment(dateStr + ' ' + timeStr).toDate();

回答by dmnk_89

var timeAndDate = moment(date).add(moment.duration(time))

When you have separated string for date and time you can parse first as date and second as duration and just add them. This should create momentwith proper date and time

当您为日期和时间分隔字符串时,您可以首先将日期解析为日期,然后将其解析为持续时间,然后添加它们。这应该moment以正确的日期和时间创建