2017-09-14 32 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