我正在使用几年前编写的脚本来检查日期是否有效:
//These values are comming from user input
var _day = 19;
var _month = 9; //October (10 - 1 for javascript Date object sake)
var _year = 1986;
var _hour = 0;
var _minute = 0;
var _second = 0;
var result;
//Checks if date is valid
var _datetime = new Date(_year, _month, _day, _hour, _minute, _second);
var _valid =
_day == _datetime.getDate()
&& _month == _datetime.getMonth()
&& _year == _datetime.getFullYear()
&& _hour == _datetime.getHours()
&& _minute == _datetime.getMinutes()
&& _second == _datetime.getSeconds();
if(_valid){
result = 'valid';
}else{
result = 'invalid';
}
document.write('The date ' + _datetime + ' is ' + result);
此日期显示为无效,因为_datetime.getHours()
正在返回1
而不是0
。
如果我将_day
值更改为 18 或 20 ,则日期会正确验证。我只是看不出有什么问题。
答案 0 :(得分:2)
可能是时区问题,请尝试UTC。
//These values are comming from user input
var _day = 19;
var _month = 9;
var _year = 1986;
var _hour = 0;
var _minute = 0;
var _second = 0;
//Checks if date is valid
var _datetime = new Date(Date.UTC(_year, _month, _day, _hour, _minute, _second));
var _valid =
_day == _datetime.getUTCDate()
&& _month == _datetime.getUTCMonth()
&& _year == _datetime.getUTCFullYear()
&& _hour == _datetime.getUTCHours()
&& _minute == _datetime.getUTCMinutes()
&& _second == _datetime.getUTCSeconds();
if(_valid){
console.log('User input is valid');
}else{
console.log('Invalid date');
}