2012-11-08 91 views
0

我比較兩個日期在JavaScript比較日期沒有返回正確的結果在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」是「12年11月10日」和「的currentdate」是「11/8/12「現在在這種情況下」如果(currentExpiryDateStr < currentDate)「返回true並且正在進入if條件,但是這個條件應該返回false並且不應該在這個if條件中進入。這是以前的工作,但不知道爲什麼它現在不工作。

回答

-1

前只需添加這2行If條件

currentExpiryDateStr=Date.parse(currentExpiryDateStr); 
currentDate=Date.parse(currentDate); 
+0

感謝polin。它的工作:) –

+1

樂於幫助:) – polin

+1

-1 Date.parse不應該用來解析字符串,因爲跨瀏覽器的一致性很差。提供非標準格式尤其糟糕。如果要使用它,則應使用[符合ECMA-262](http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15)(例如ISO8601)的格式,但它在某些瀏覽器中會失敗,並且應該檢查結果。 – RobG

0

Date對象會做你想做的 - 爲每個日期構造一個,然後使用通常的操作符比較它們。 試試這個..

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; 
    } 
    } 

這裏是小提琴:: http://jsfiddle.net/YFvAC/3/

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日

0

你比較字符串,你應該比較日期對象。

如果expriy日期的格式爲月/日/年'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; 
} 

所以在8 - 11月,2012:

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 
} 
+0

羅布我看到你的方法,但有一個問題。如果我檢查相等(==)的條件。然後它失敗了,因爲它也在比較時間。 –

+0

我想我會用getTime() –

相關問題