Javascript moment.js 连接日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42404507/
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:07:26  来源:igfitidea点击:

moment.js concatenate date and time

javascriptdatedatepickermomentjs

提问by grankan

I have four fields in a form, some containing an initial date and the end date (dd / mm / yyyy) and the others contain the start time and the end time (hh: ss).

我在一个表单中有四个字段,一些包含初始日期和结束日期 (dd / mm / yyyy),其他包含开始时间和结束时间 (hh: ss)。

The value of these fields I use to get the date and time with moment.js such as this:

我用来通过 moment.js 获取日期和时间的这些字段的值,例如:

initialdate = moment( $('input#start_date').val(), 'DD/MM/YYYY' );
start_time = moment( $('input#start_time').val(), 'HH:mm');
enddate = moment( $('input#enddate').val(), 'DD/MM/YYYY' );
end_time = moment( $('input#end_time').val(), 'HH:mm');

What I intend is to then get the difference in seconds between the two dates, concatenating the starting date and time and the ending date and time. I have tried to do this, but to no avail:

我打算然后获得两个日期之间的秒差,连接开始日期和时间以及结束日期和时间。我试图这样做,但无济于事:

start = initialdate + start_time;
end = enddate + end_time;
tracker = moment.duration( end.diff(start) ).asSeconds();

采纳答案by mehparra

The fail is trying on concatenate the values, test with something like this:

失败是尝试连接值,使用以下内容进行测试:

let initialdate = '2016-10-01';
let start_time = '19:04:10';
let enddate = '2016-10-01';
let end_time = '19:04:20';

let datetimeA = moment(initialdate + " " + start_time);
let datetimeB = moment(enddate + " " + end_time);

console.log(datetimeA.format());
console.log(datetimeB.format());

let datetimeC = datetimeB.diff(datetimeA, 'seconds');

console.log(datetimeC);

回答by RobG

Concatenate the date and time strings and parse them as one, e.g.

连接日期和时间字符串并将它们解析为一个,例如

var date = '23/02/2017';
var time = '15:42';

var dateTime = moment(date + ' ' + time, 'DD/MM/YYYY HH:mm');

console.log(dateTime.format('YYYY-MM-DD HH:mm'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>

回答by ahota

A much cleaner solution IMO is to use moment's hourand minutegetters and setters.

IMO 更简洁的解决方案是使用 momenthourminutegetter 和 setter。

let a = moment()
let b = moment().add(3, 'hour').add(37, 'minute') //b is the time portion
a.hour(b.hour()).minute(b.minute())

回答by Sergei Volynkin

[2019] Most elegant solution is:

[2019] 最优雅的解决方案是:

/* "date" and "time" are instances of Moment */

    date = date.set({
          hour: time.get('hour'),
          minute: time.get('minute'),
          second: 0,
          millisecond: 0,
        });