2014-02-19 110 views
0

在日期選擇器中,我想限制輸入以防止過去的日期。我使用了下面的JavaScript,但在某些情況下它失敗了。使用Javascript計算給定日期是當前日期還是將來日期?

function isPastDate(value) { 
     var now = new Date; 
     var target = new Date(value); 

     if (target.getFullYear() < now.getFullYear()) { 
      return true; 
     } else if (target.getMonth() < now.getMonth()) { 
      return true; 
     } else if (target.getDate() < now.getDate()) { 
      return true; 
     } 
    return false; 
} 

有人可以幫我嗎?

+1

在這情況下它會失敗? –

+3

你已經結束了一件簡單的事情'console.log(now> target)' – epascarello

+0

有人從這裏複製了答案:http://stackoverflow.com/questions/17344318/javascript-to-allow-only-current-and-未來日期? – epascarello

回答

4

由於epascarello指出,簡單地比較兩個日期:

function isPastDate(value) { 
    return new Date() > new Date(value); 
} 

這是因爲日期以毫秒爲單位自1970年1月1日(糾正我,如果我測量錯誤),所以真正發生的是兩個長數字之間的比較。

+0

如果你想在稍後使用它,你可以使用時間戳。 如果不是,這種方法工作正常。 查看[這篇文章](http://stackoverflow.com/questions/11893083/convert-normal-date-to-unix-timestamp)JavaScript時間戳。 –

1

this post

var selectedDate = $('#datepicker').datepicker('getDate'); 
var now = new Date(); 
if (selectedDate < now) { 
    // selected date is in the past 
} 
-1

您的功能在邏輯上是錯誤的,並且在測試月份之前如果年份實際上是相同的,那麼也不會檢查這些年份,相同的月份和日期也是如此。 你可以試試:

function isPastDate(value) { 
    var now = new Date; 
    var target = new Date(value); 

    if (target.getFullYear() < now.getFullYear()) { 
     return true; 
    } else if (target.getFullYear() === now.getFullYear()) 
     if (target.getMonth() < now.getMonth()) { 
      return true; 
     } else if (target.getMonth() === now.getMonth()) { 
      if (target.getDate() < now.getDate()) { 
       return true; 
      } 
     } 
    } 

    return false; 
} 

希望幫助