如何使用javascript验证日期(当月的最后一天)? [英] How to validate date if is the last day of the month with javascript?
问题描述
如何使用javascript验证用户输入日期是月份的最后一天?
How to validate user input date is the last day of the month using javascript?
推荐答案
(更新:请参见底部的最后一个示例,其余部分作为背景.)
(Update: See the final example at the bottom, but the rest is left as background.)
您可以在 Date
实例中添加一天,并查看月份是否发生了变化(因为JavaScript的 Date
对象智能地修正了无效的每月日期值),例如:
You can add a day to the Date
instance and see if the month changes (because JavaScript's Date
object fixes up invalid day-of-month values intelligently), e.g.:
function isLastDay(dt) {
var test = new Date(dt.getTime()),
month = test.getMonth();
test.setDate(test.getDate() + 1);
return test.getMonth() !== month;
}
...或 paxdiablo 指出,您可以检查结果的每月日期,这大概是更快(减少了一个函数调用),并且肯定短了一些:
...or as paxdiablo pointed out, you can check the resulting day-of-month, which is probably faster (one fewer function call) and is definitely a bit shorter:
function isLastDay(dt) {
var test = new Date(dt.getTime());
test.setDate(test.getDate() + 1);
return test.getDate() === 1;
}
如果愿意的话,您可以在其中嵌入更多逻辑,以避免创建临时日期对象,因为它仅在二月份才真正需要它们,其余的只是表查找,但是两者的优点以上是他们将 all 日期数学推迟到JavaScript引擎.创建对象不会花费太多的钱.
You could embed more logic in there to avoid creating the temporary date object if you liked since it's really only needed in February and the rest is just a table lookup, but the advantage of both of the above is that they defer all date math to the JavaScript engine. Creating the object is not going to be expensive enough to worry about.
...最后:由于 JavaScript规范要求(第15.9.1.1节)准确地一天长 86,400,000毫秒(实际上,天
...and finally: Since the JavaScript specification requires (Section 15.9.1.1) that a day is exactly 86,400,000 milliseconds long (when in reality days vary in length a bit), we can make the above even shorter by adding the day as we :
function isLastDay(dt) {
return new Date(dt.getTime() + 86400000).getDate() === 1;
}
这篇关于如何使用javascript验证日期(当月的最后一天)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!