2017-06-02 57 views
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) 

我应该如何获得当我通过这两个字符串这个失败。谢谢。另外是怎么回事,为什么它没有失败,也将是有益的:)

+1

您必须手动检查'+ arrayDate [3] == date.getFullYear()|| + arrayDate [2]!== date.getMonth()|| <相同的日期>' – Rajesh

+1

我有这个问题。虽然不是欺骗,你会从这篇文章得到的帮助:https://codereview.stackexchange.com/questions/109765/javascript-date-validation – Rajesh

+0

@Rajesh谢谢,我做了一些修改,你给的代码,在其上添加下方行已经存在的代码,它按预期工作。我增加了得到月()+ 1,因为指数为它从0开始为该函数单独 '变种有效= + arrayDate [3] === actualDate.getFullYear()&& + arrayDate [2] === actualDate.getMonth ()+ 1 && + arrayDate [1] === actualDate.getDate(); 印刷(有效期);' –

回答

1

这个例子可以帮助你:

var dateString = 'Mon Jun 24 2013 05:30:00 GMT+0530 (India Standard Time)'; 
var myDate = new Date(dateString); 
var final_date = myDate.getDate()+"-"+(myDate.getMonth()+1)+"-"+myDate.getFullYear(); 

在这里你可以验证每个变量为日,月,年。

+0

有点晚,对不起,我错过了这个答案,谢谢它的工作! –