Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
134
rated 0 times [  139] [ 5]  / answers: 1 / hits: 20655  / 13 Years ago, wed, june 15, 2011, 12:00:00

How to validate user input date is the last day of the month using javascript?


More From » javascript

 Answers
16

(Update: See the final example at the bottom, but the rest is left as background.)



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;
}


Gratuitous live example



...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;
}


Another gratuitous live example



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.






...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;
}


Final gratuitous example


[#91701] Tuesday, June 14, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elishaannac

Total Points: 28
Total Questions: 97
Total Answers: 101

Location: Samoa
Member since Mon, Nov 8, 2021
3 Years ago
;