简体   繁体   English

防止Javascript创建日期过长的日期

[英]Prevent Javascript from creating dates with a large months

In Javascript if I create a date like so: 在Javascript中,如果我这样创建日期:

var y=new Date('2014','16','06')

Then y will be on my computer Wed May 06 2015 00:00:00 GMT-0400 . y将在我的计算机Wed May 06 2015 00:00:00 GMT-0400 However, the month I entered is 16 not 5 . 但是,我输入的月份是16而不是5 Is there anyway to prevent Javascript from creating a valid date in this instance (when Month is too big) and just return 'Invalid Date'? 是否有任何方法可以防止Javascript在这种情况下(当Month太大时)创建有效日期并仅返回“无效日期”?

Here's the relevant information from the Mozilla Javascript documentation for Date : 以下是Mozilla Javascript文档中有关Date的相关信息:

Note: Where Date is called as a constructor with more than one argument, if values are greater than their logical range (eg 13 is provided as the month value or 70 for the minute value), the adjacent value will be adjusted. 注意:如果将Date用作具有多个参数的构造函数,则如果值大于其逻辑范围(例如,将13作为月份值或将70作为分钟值),则会调整相邻的值。 Eg new Date(2013,13,1) is equivalent to new Date(2014,1,1), both create a date for 2014-02-01 (note that the month is 0-based). 例如,新的Date(2013,13,1)等同于新的Date(2014,1,1),两者都为2014-02-01创建一个日期(请注意,该月是从0开始的)。 Similarly for other values: new Date(2013,2,1,0,70) is equivalent to new Date(2013,2,1,1,10) which both create a date for 2013-03-01T01:10:00. 同样,对于其他值:new Date(2013,2,1,0,70)等同于new Date(2013,2,1,1,10),两者都会为2013-03-01T01:10:00创建一个日期。

So in answer, no, that's the only behavior of the Date constructor, and any validation you want to do on your input values is going to have to be done by you before you pass them into the constructor. 因此,在回答中,不,这是Date构造函数的唯一行为,在将它们传递到构造函数之前,您必须对输入值进行任何验证。

However, one possible option could be to concatenate a string of your date value and then use Date.parse() on it, which will return a valid value if your date is correct or NaN if it isn't. 但是,一种可能的选择是连接日期值的字符串,然后在其上使用Date.parse() ,如果日期正确,则返回有效值,否则返回NaN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM