moment.js连接日期和时间

时间:2017-02-22 23:50:41

标签: javascript date datepicker momentjs

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

我使用这些字段的值来获取带有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');

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

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

5 个答案:

答案 0 :(得分:16)

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



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>
&#13;
&#13;
&#13;

答案 1 :(得分:14)

失败是试图连接值,测试类似的东西:

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

答案 2 :(得分:4)

一个更清洁的解决方案IMO将使用片刻的hourminute getter和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())

答案 3 :(得分:2)

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

/* "date" and "time" are moment() objects */

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

答案 4 :(得分:0)

简单使用这个功能

function getCombinedDateObject(date, time) {
let calculatedDateString = '';
if (date && time) {
  let utcDate = moment.utc(date);
  let utcTime = moment.utc(time);
  calculatedDateString = moment(`${utcDate.format('YYYY-MM-DD')} ${utcTime.format("HH:mm:ss z")}`);
}
let finalDateTime = new Date(calculatedDateString);
if (isNaN(finalDateTime.getTime()))
  return null;
else
  return finalDateTime;
}