我有 2 个字段输入和输出日期。在某些情况下,我将结束日期设置为比开始日期提前 1 年。
<input type='date' id='endDate'>
$("#startDate").change(function(){
var endDate = new Date($("#startDate").val());
endDate.setMonth(endDate.getMonth() + 1);
endDate.setFullYear(endDate.getFullYear() + 1);
var myDay = ("0" + endDate.getDate()).slice(-2);
var myMonth = ("0" + endDate.getMonth()).slice(-2);
$("#endDate").val(endDate.getFullYear() + '-' + myMonth + '-' + myDay);
}
当我将开始日期设置为 2-29-2016 时的问题 我收到以下错误:
The specified value "2017-02-29" does not conform to the required format, "yyyy-MM-dd".
我希望 Date() 函数能够处理它。显然,他们没有。这是一个错误吗?
他们是否比添加一堆 if 语句更快?
最佳答案
The specified value "2017-02-29" does not conform to the required format, "yyyy-MM-dd".
2017-02-29
不是有效日期。 29th feb
明年 (2017) 是不可能的。
只有闰年才有二月二十九。
改为尝试 2016-02-29
。
Is their anyway faster than adding a bunch of if statements?
不需要添加一堆 if 语句,你可以使用这个 answer
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
为了回答您的问题,如果您将日期明确设置为“2017-02-29”,则会引发错误。
只需更改日期对象本身并将该日期对象应用于输入
$("#endDate").val( endDate.toJSON().slice(0,10) );
现在它应该负责滚动到下个月。
编辑(根据 TJ 的评论)
除了能被 100 整除的年份(非闰年)和能被 400 整除的年份(闰年)外,每年都出现闰年。
关于javascript - 输入类型日期错误的设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35429305/