Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate date if is the last day of the month with javascript?

Tags:

javascript

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

like image 251
Fire Hand Avatar asked Jun 15 '11 08:06

Fire Hand


People also ask

How do you check if a date is a valid date in JavaScript?

Using the isFinite() Method In JavaScript, the instanceof operator allows us to check whether the variable is an instance of the Date() class or not. We will check for that first, and if it is, we will check that the getTime() method returns the finite number of milliseconds or not.

How do I get the last Sunday of the month in JavaScript?

A function to get the last Sunday of a month might be: /** * Returns last Sunday of month * * @param {Temporal. YearMonth} queryMonth - YearMonth to get last Sunday of * @returns {Temporal. Date} for last Sunday of queried month */ function getLastSunday(queryMonth) { let lastOfMonth = queryMonth.


1 Answers

(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

like image 160
T.J. Crowder Avatar answered Oct 10 '22 11:10

T.J. Crowder