0

我在 javascript 中比较两个日期

function checkCurrentDate(expiryDate){
//var currentDateStr=expiryDate;
var currentDate = new Date();
var month = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var year = currentDate.getFullYear();
currentDate = month + "/" + day + "/" + year;
var dArr = currentDate.split("/");
currentDate = dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);  
var currentExpiryDateStr = expiryDate;

if(currentExpiryDateStr == currentDate){    

} 

if(currentExpiryDateStr < currentDate){

    alert("Expiry date is earlier than the current date.");
    return false;
}
}

目前日期在“currentExpiryDateStr”是“11/10/12”和“currentDate”是“11/8/12”现在在这种情况下“if(currentExpiryDateStr < currentDate)”返回true并进入if条件但是此条件应返回 false 并且不应进入此 if 条件。它以前可以工作,但不知道为什么现在不能工作。

4

4 回答 4

0

The Date object will do what you want - construct one for each date, then just compare them using the usual operators. try this..

function checkCurrentDate(expiryDate){

   var currentDate = new Date();  // now date object

  var currentExpiryDateStr = new Date(expiryDate);  //expiry date object

   if(currentExpiryDateStr == currentDate){    

   } 

   if(currentExpiryDateStr < currentDate){

         alert("Expiry date is earlier than the current date.");
         return false;
    }
   }

here is the fiddle:: http://jsfiddle.net/YFvAC/3/

于 2012-11-08T06:05:12.190 回答
0

您正在比较字符串,您应该比较日期对象。

如果到期日期是月/日/年格式的“11/10/12”,并且年份是 2000 年之后的两位数年份,则可以使用以下方法将其转换为日期:

function mdyToDate(dateString) {
  var b = dateString.split(/\D/);
  return new Date('20' + b[2], --b[0], b[1]);
}

要测试到期,您可以执行以下操作:

function hasExpired(dateString) {
  var expiryDate = mdyToDate(dateString);
  var now = new Date();
  return now > expiryDate;
}

所以在 2012 年 11 月 8 日:

hasExpired('11/10/12'); // 10-Nov-2012 -- false
hasExpired('6/3/12');   // 03-Jun-2012 -- true

hasExpired功能可以替换为:

if (new Date() > mdyToDate(dateString)) {
  // dateString has expired
}
于 2012-11-08T06:12:27.303 回答
0
var currentDate = Date.now();
if (expiryDate.getTime() < currentDate ) {
    alert("Expiry date is earlier than the current date.");
    return false;
}

now()方法返回自 1970 年 1 月 1 日 00:00:00 UTC 到现在为止经过的毫秒数。

getTime()返回自 1970 年 1 月 1 日午夜以来的毫秒数

于 2012-11-08T06:08:12.463 回答
-1

Just add this 2 lines before your if condition

currentExpiryDateStr=Date.parse(currentExpiryDateStr);
currentDate=Date.parse(currentDate);
于 2012-11-08T06:05:42.193 回答