2010-09-24 45 views
0

我正在处理2个日期,这些日期在文本框中以这种格式作为字符串发布给我03/02/2010。一个是当前完成日期,第二个是最终完成日期。我需要比较这两个日期,以检查最终完成日期是否在当前完成日期的前面,后面或相同。如何查看2个日期字段并比较查看哪个日期在前面,后面或相同

有没有一种方法可以使用JavaScript或jQuery来做到这一点?

感谢您的任何帮助。

回答

2
var passedDate1 = new Date('03/02/2010'); 
var passedDate2 = new Date('03/01/2010'); 

if (passedDate1 > passedDate2) { 
    alert ('Date1 is greated than date 2'); 
} 
else if (passedDate1 < passedDate2) { 
    alert ('Date1 is less than date 2'); 
} 
else { 
    alert ('they are equal'); 
} 
+0

非常感谢约翰,这正是我需要的东西! – Cliftwalker 2010-09-27 10:25:28

0

将其转换为美国格式

function dateUS(date) 
{ 
    var date = date.split("/"); 
    return date[2] + '/' + date[1] + '/' + date[0]; 
} 

然后

if(dateUS(dateCurrent) < dateUS(dateFinal)) 
{ 
    //your code 
} 
0
var doc = document, 
dateBox1 = doc.getElementById("date1").value, 
dateBox2 = doc.getElementById("date2").value, 
d1, d2, diff; 

//if there is no value, Date() would return today 
if (dateBox1) { 
    d1 = new Date(dateBox1); 
} else { 
    //however you want to handle missing date1 
} 
if (dateBox1) { 
    d2 = new Date(dateBox2); 
} else { 
    //however you want to handle missing date2 
} 
if (d1 && d2) { 
    //reduce the difference to days in absolute value 
    diff = Math.floor(Math.abs((d1 - d2) /1000/60/60/24)); 
} else { 
    //handle not having both dates 
} 
if (diff === 0) { 
    //d1 and d2 are the same day 
} 
if (diff && d1 > d2) { 
    //d1 is diff days after d2 and the diff is not zero 
} 
if (diff && d1 < d2) { 
    //d1 is diff days before d2 and the diff is not zero 
}