2014-03-30 85 views
0

我必須檢查兩個日期是否相差超過兩天。舉例來說,2014年1月14日和2014年1月15日將符合標準,因爲只有一天的差異,但2014年1月14日和2014年1月18日不會像後者有4天差異。日期是字符串格式,所以我嘗試了各種數據轉換,但無法成功。總結一下,我想知道是否可以創建一個if語句,該語句將字符串格式的兩個日期的值相減,如果該值大於「n」,則會發出錯誤。謝謝!是否有可能在JavaScript中進行日期驗證?

+2

是的,這是可能的。 – Bergi

+1

http://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript/15289883#15289883 – JohanVdR

+0

你真的不知道這一點? - >'if((new Date('01/14/2015').getTime() - new Date('01/15/2014').getTime())>(1000 * 60 * 60 * 24 * 2) )' – adeneo

回答

0
// https://gist.github.com/remino/1563878 
// Converts millseconds to object with days, hours, minutes ans seconds. 
function convertMS(ms) { 
    var d, h, m, s; 
    s = Math.floor(ms/1000); 
    m = Math.floor(s/60); 
    s = s % 60; 
    h = Math.floor(m/60); 
    m = m % 60; 
    d = Math.floor(h/24); 
    h = h % 24; 
    return { d: d, h: h, m: m, s: s }; 
}; 

var start_date = '04/15/2014'; 
var end_date = '04/16/2014'; 

var diff = convertMS(Date.parse(end_date) - Date.parse(start_date)); 

if(diff.d > 1) { 
    console.log('The difference is more than one day!'); 
} 
else { 
    console.log('The difference is just one day and therefore accepted!'); 
} 

見JS小提琴:http://jsfiddle.net/E7bCF/11/
看到JS撥弄超過一天的區別更多:http://jsfiddle.net/E7bCF/9/

0

嘗試

new Date("MM/DD/YYYY") - new Date("MM/DD/YYYY") 

,將返回以毫秒爲單位的數字。

+0

這不是'DD/MM/YYYY'(不幸) – Bergi

+0

我的錯誤;固定 – itdoesntwork

1

一個解決方案是使用簡單的字符串解析爲每個日期創建一個Javascript Date對象(http://www.w3schools.com/js/js_obj_date.asp),使用.getTime()函數獲取以毫秒爲單位的值並檢查它是否大於1000 x 60 x 60 x 24 x 2。