2017-09-14 28 views
0

我该如何检查是否是第二天?MomentJS检查是否第二天,并分开几天

const startDate = moment(item.start_time); 
const endDate = moment(item.end_time); 
const dateDiff = startDate.diff(endDate, 'days', true) 
const nextDay = dateDiff > 1 

它的工作原理像8月14日下午2时至8月14日下午4点日期但它并没有像8月14日下午4点至8月14日下午2日期工作。

我该如何解决?

如果可能我希望得到他们分开的天数。

const startDate = moment(item.start_time); 
const endDate = moment(item.end_time); 
const dateDiff = startDate.diff(endDate, 'days', true) mod 1 
+0

'start_time'格式时间戳或日期对象? – nivas

+0

这是一个JavaScript日期 –

回答

1

使用getDate & setDate方法精确地以一天增加当前日期的对象。之后,您只需比较日期年,月和日期。

var isNextDay = function(next, current) { 
 
    var date = new Date(current); 
 
    date.setDate(date.getDate() + 1); 
 
    
 
    return (date.getFullYear() === next.getFullYear()) && (date.getMonth() === next.getMonth()) && (date.getDate() === next.getDate()); 
 
}; 
 

 
var currentDay = new Date('2016-05-31 16:00:00'); 
 
var nextDay = new Date('2016-06-01 14:00:00'); 
 
console.log('It is ' + (isNextDay(nextDay, currentDay) ? '' : 'not ') + 'the next day');

+0

如果是5月31日和6月1日,该怎么办? –

+0

@ShinonChan请检查更新的解决方案 –

0

检查这个代码:

var currentDay =new moment('2016-05-31 16:00:00'); 
var nextDay = new moment('2016-06-01 14:00:00'); 

console.log('It is ' + (nextDay.isSame(currentDay.add(1, 'days'), 'd') === true ? '' : 'not ') + 'the next day'); 

jsfiddle