Reputation: 26396
How to validate user input date is the last day of the month using javascript?
Upvotes: 24
Views: 25645
Reputation: 2028
If you want to avoid reinventing the wheel and having extra code to maintain and test, I highly suggest to use an external library like Moment.js or date-fns.
I personally advocate for date-fns as it is not as bulky as Moment and relies on Date primitives rather than Moment objects.
Your function of interest is named isLastDayOfMonth
and can be found here
Upvotes: 0
Reputation: 541
function isLastDayOfMonth(date){
return date.getDate() == new Date(date.getFullYear(),date.getMonth()+1,0).getDate();
}
Upvotes: 1
Reputation: 1075039
(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;
}
...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;
}
Upvotes: 39
Reputation: 686
This is worked.
var lastday = new Date(new Date().getFullYear(),new Date().getMonth()+1,0).getDate();
Hope help you.
Upvotes: 1
Reputation: 708
Suppose that you got:
var month = getMonthFromUserInput();
var year = getYearFromUserInput();
This will give the last day of that month
new Date((new Date(year , month , 1)) -1 )
Remember that month 0 is Jan
Upvotes: 0
Reputation: 3504
Browsers identify the day 0 as the last day of the previous month
var month = 0; // January
var d = new Date(2008, month + 1, 0);
alert(d); // last day in January
as seen here : Calculate last day of month in javascript
you can simply use the month inserted by the user + 1 with day = 0 to check if he has inserted the last day of the month.
Upvotes: 1