2013-06-24 40 views
0

如果你看我的日期驗證當我來測試它是否在過去它工作,雖然日期構造函數期望一個零日期月,所以我如何從子字符串值中減去一個代表月份(從結果之一,而不是位置)如何調整substr中的日期構造函數javascript

//start of datefield 
var dateformat=/^(?:(?:31\/(?:0[13578]|1[02])|(?:29|30)\/(?:0[13-9]|1[012])|(?:0[1-9]|1\d|2[0-8])\/(?:0[1-9]|1[0-2]))\/[2-9]\d{3}|29\/02\/(?:[2-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[3579][26])00))$/; 
if (!date.match(dateformat)) 
{ 
     errors.push("format incorrect use dd/mm/yyyy make sure you are entering correct days to the month remember 30 days have september, april, june & november, only 28 days in february unless leap year next is 2016"); 

} 
var today = new Date(); 

var courseYear =date.substr(6,4) // use substr or substring to capture the last four digits 
var courseMonth =date.substr(3,2) // use substr or substring to capture the four and fifth digits 
var courseDay = date.substr(0,2)//e the first and second digits 

var dateToCompare = new Date(courseYear, courseMonth, courseDay); 

if (dateToCompare < today) { 
    errors.push("this date is in the past"); 

} 
+1

你問如何將字符串轉換爲數字? – SLaks

+2

你是否認真地嘗試檢測正則表達式中的閏年? – Bergi

+0

沒有對不起,基本上我的var coursemonth構造函數期望0基於月,所以jan是0 feb是1等等,所以當我做檢查,看看日期是否在過去,我輸入說25/05/2013這通過由於腳本認爲5實際上是6月。所以我想知道如何從substr值中扣除一個代表 – adam

回答

3

讓我怎麼減一

隨着subtraction operator "-"和數字字面「1」。它還具有將字符串轉換爲數字的好處。對於一年的一天,你可以使用一元加號做明確的轉換(雖然Date構造函數它含蓄地):

new Date(+courseYear, courseMonth-1, +courseDay); 
+0

謝謝你,這是不能相信我錯過了歡呼聲 – adam

相關問題