0
我有一個輸入日期字符串,像這樣「30/09/1992」,我發現這個代碼,以滿足我的需要。 PFB的代碼。javascript日期轉換不會失敗
var input1 = "30/09/1992";
var isVaidDate = false;
var actualDate = "";
try{
var pattern = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
var arrayDate = input1.match(pattern);
var actualDate = new Date(arrayDate[3], arrayDate[2] - 1, arrayDate[1]);
var isVaidDate = typeof dt.getMonth === 'function';
}catch(e){var output1 = false;}
print(isVaidDate);
print(actualDate);
上面的代碼工作正常,但是當我設置的輸入爲「31/09/1992」或「40/09/1992」我期待無效的日期來到,但我得到下面的輸出。
爲 「31/09/1992」:
true
Thu Oct 01 1992 00:00:00 GMT+0530 (India Standard Time)
爲 「40/09/1992」:
true
Thu Oct 10 1992 00:00:00 GMT+0530 (India Standard Time)
我應該如何獲得當我通過這兩個字符串這個失敗。謝謝。另外是怎麼回事,爲什麼它沒有失敗,也將是有益的:)
您必須手動檢查'+ arrayDate [3] == date.getFullYear()|| + arrayDate [2]!== date.getMonth()|| <相同的日期>' – Rajesh
我有這個問題。雖然不是欺騙,你會從這篇文章得到的幫助:https://codereview.stackexchange.com/questions/109765/javascript-date-validation – Rajesh
@Rajesh謝謝,我做了一些修改,你給的代碼,在其上添加下方行已經存在的代碼,它按預期工作。我增加了得到月()+ 1,因爲指數爲它從0開始爲該函數單獨 '變種有效= + arrayDate [3] === actualDate.getFullYear()&& + arrayDate [2] === actualDate.getMonth ()+ 1 && + arrayDate [1] === actualDate.getDate(); 印刷(有效期);' –