在 JavaScript 中检查日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6800253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check date in JavaScript
提问by js-coder
I get three variables through a user input, that contain the year of a date, the month and the day. I've already checked if the month var is between 1–12 and so on.
我通过用户输入获得三个变量,其中包含日期的年份、月份和日期。我已经检查过月份变量是否在 1-12 之间等等。
Now I want to check if it's a real date and not a date that doesn't exist like 31–06–2011.
现在我想检查它是否是真实日期,而不是像 31–06–2011 这样不存在的日期。
My first idea was to make a new Date instance:
我的第一个想法是创建一个新的 Date 实例:
var year = 2011;
var month = 5; // five because the months start with 0 in JavaScript - June
var day = 31;
var myDate = new Date(2011,5,31);
console.log(myDate);
But myDate doesn't return false, because it's not a valid date. Instead it returns 'Fri Jul 01 2011 [...]'.
但 myDate 不会返回 false,因为它不是有效日期。相反,它返回“Fri Jul 01 2011 [...]”。
Any ideas how I can check for an invalid date?
任何想法如何检查无效日期?
回答by Gaurav
Try this:
试试这个:
if ((myDate.getMonth()+1!=month)||(myDate.getDate()!=day)||(myDate.getFullYear()!=year))
alert("Date Invalid.");
回答by Sergey Metlov
if ((myDate.getDate() != day) ||
(myDate.getMonth() != month - 1) ||
(myDate.getFullYear() != year))
{
return false;
}
JavaScript just converts entered in Date
constructor month
, year
, day
, etc.. in simple int value (milliseconds) and then formats it to represent in string format. You can create new Date(2011, 100, 100)
and everythig will ok :)
JavaScript的只是转换在进入Date
构造函数month
,year
,day
,等简单的int值(毫秒)..然后格式化它以字符串格式表示。你可以创建new Date(2011, 100, 100)
,一切都会好的:)
回答by dbb
You could possibly do what you do now and construct a new Date object and then afterwards check the value of myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), to ensure that those values match the input values. Keep in mind that getMonth() and getDate() are 0 indexed, so January is month 0 and December is month 11.
您可以按照现在的操作构建一个新的 Date 对象,然后检查 myDate.getFullYear()、myDate.getMonth()、myDate.getDate() 的值,以确保这些值与输入值匹配。请记住,getMonth() 和 getDate() 索引为 0,因此一月是 0 月,十二月是 11 月。
Here's an example:
下面是一个例子:
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
}
console.log(isValidDate(2011,5,31));
console.log(isValidDate(2011,5,30));
回答by neoerol
I think this way true.
我认为这种方式是正确的。
function isValidDate(year, month, day) {
var d = new Date(year, month, day);
if(month == 12){
year = parseInt(year)*1+1*1;
month = 0;
}
day = parseInt(day);
month = parseInt(month);
year = parseInt(year);
if(month === 2 && day > 29){
return false;
}
return d.getFullYear() === year && d.getMonth() === month && d.getDate() === day;
}