beliy333 beliy333 - 15 days ago 6
jQuery Question

How to write conditional - if current date and time is before last day of month 11:59

With JavaScript how would I write a conditional statement checking if the current date and time (UTC), is before the last day 11:59 pm of current month. I don't want to use third-part libraries.

For example:

Date must be in UTC timezone.

if(todays_date_and_time < this_months_last_day_at_11_and_59pm) {
function1();
} else {
function2();
}

Answer

Actually, the solution is very simple.

// This is function which checks your date

function checkDate(ms){
    ms = ms || Date.now();
    return (new Date(ms)).getUTCDate() <= (new Date(ms + 6e4)).getUTCDate();
}

checkDate(); // Check current date
checkDate(1479586906627); // Check specified date

// If you want if statement, you can do it as following

if(checkDate()){
    function1();
}else{
    function2();
}

How does it work? It checks if we can reach next month in one minute. If yes, it means that new day of the month will be smaller than the current day, so it simply compares these two values.

Comments