Skip to content Skip to sidebar Skip to footer

First Tuesday Of Every Month

Hello I am trying to use the following code which is a mish mash of 'lifted code' but it keeps pumping out todays date and time. I am trying to get the date for the first Tuesday

Solution 1:

Use below function, that will give you current month Tuesdays.

functiongetTuesday() {
    var d = newDate(),
        month = d.getMonth(),
        tuesdays= [];

    d.setDate(1);

    // Get the first Monday in the monthwhile (d.getDay() !== 2) {
        d.setDate(d.getDate() + 1);
    }

    // Get all the other Tuesdays in the monthwhile (d.getMonth() === month) {
        tuesdays.push(newDate(d.getTime()));
        d.setDate(d.getDate() + 7);
    }

    return tuesdays;
}

Solution 2:

I know that this is old but this is a function that i wrote based on what Sahal wrote that accepts a few additional features. Ill go through the arguments and returns below.

functiongetDates(dayString, month, year, first, allInYear) {
    if (!dayString) { console.error('Missing required parameter: dayString is required.'); return; }
    if (first === undefined || first === null) { first = false; }
    if (allInYear === undefined || allInYear === null) { allInYear = false; }
    if (year === undefined || year === null) { year = newDate().getFullYear(); }
    var converted = false;
    if (month === undefined || month === null) {
        var temp = newDate();
        if (temp.getDate() > 9) {
            month = ((temp.getMonth() + 1) == 12) ? 11 : (temp.getMonth() + 1);
        } else {
            month = temp.getMonth();
        }
        converted = true;
    }
    if (typeof month === "string" && isNaN(parseInt(month))) {
        month = month.toLowerCase().substring(0, 3);
        switch (month) {
            case"jan":
                month = 0;
                break;
            case"feb":
                month = 1;
                break;
            case"mar":
                month = 2;
                break;
            case"apr":
                month = 3;
                break;
            case"may":
                month = 4;
                break;
            case"jun":
                month = 5;
                break;
            case"jul":
                month = 6;
                break;
            case"aug":
                month = 7;
                break;
            case"sep":
                month = 8;
                break;
            case"oct":
                month = 9;
                break;
            case"nov":
                month = 10;
                break;
            case"dec":
                month = 11;
                break;
            default:
                var temp = newDate();
                if (temp.getDate() > 9) {
                    month = ((temp.getMonth() + 1) == 12) ? 11 : (temp.getMonth() + 1);
                } else {
                    month = temp.getMonth();
                }
                converted = true;
                break;
        }
    } elseif (typeof month === "number" || (typeof month === "string" && !isNaN(parseInt(month)))) {
        month = (!converted) ? parseInt(month) - 1 : month;
    }
    if (typeof year === "string" && !isNaN(parseInt(year)) || typeof year === "number") {
        if (parseInt(year) / 1000 > 2) {
            year = parseInt(year);
        } elseif (parseInt(year) / 10 >= 0 && parseInt(year) / 10 < 10) {
            var temp2 = newDate().getFullYear();
            year = (parseInt(Math.floor(temp2 / 100)) * 100) + parseInt(year);
        }
    } elseif (typeof year === "string" && isNaN(parseInt(year))) {
        if (year === "this") {
            year = newDate().getFullYear();
        } elseif (year === "last") {
            year = newDate().getFullYear() - 1;
        } elseif (year === "next") {
            year = newDate().getFullYear() + 1;
        } else {
            console.warn('Year string not recognized, falling back to current year. (this, last, next).');
            year = newDate().getFullYear();
        }
    }
    var dates = [];
    //hang in there this is going to get a doosievar d = newDate(),
        dow = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"],
        getDow = function(sd, dowa) {
            for (var i = 0; i < dowa.length; i++) {
                var day = dowa[i];
                if (sd.toLowerCase().substring(0, 3) == day) {
                    return i;
                }
            }
            return -1;
        },
        di = getDow(dayString, dow),
        getDIM = function(year, mon) {
            var isLeap = ((year % 4) == 0 && ((year % 100) != 0 || (year % 400) == 0));
            return [31, (isLeap ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][mon];
        };
    d.setFullYear(year);
    d.setMonth(month, 1);
    if (di == -1) { console.error('Range Error: Day of the week should be between sunday and saturday'); return; }
    if (first && !allInYear) {
        while (d.getDay() !== di) {
            d.setDate(d.getDate() + 1);
        }
        return d;
    } elseif (first && allInYear) {
        var tm = 0;
        d.setMonth(tm, 1);
        for (var i = tm; i <= 11; i++) {
            while (d.getDay() !== di) {
                d.setDate(d.getDate() + 1);
            }
            dates.push(newDate(d));
            tm += 1;
            d.setMonth(tm, 1);
        }
        return dates;
    } elseif (!first && !allInYear) {
        var eom = getDIM(d.getFullYear(), d.getMonth());
        for (var x = 1; x <= eom; x++) {
            if (d.getDay() === di) {
                dates.push(newDate(d));
            }
            d.setDate(d.getDate() + 1);
        }
        return dates;
    } elseif (!first && allInYear) {
        var tm = 0;
        for (var i = 0; i <= 11; i++) {
            var eom = getDIM(d.getFullYear(), i),
                dim = [];
            d.setMonth(i, 1);
            for (var x = 1; x <= eom && d.getMonth() == i; x++) {
                if (d.getDay() === di) {
                    dim.push(newDate(d));
                }
                d.setDate(d.getDate() + 1);
            }
            dates.push(dim);
        }
        return dates;
    } else {
        return [];
    }
}

So the only required argument is the day string, optionally you can set month,year,first or all in a month and all in a year or not, month and year default to current, and first and allInYear default to false, But you can set first in moth, by passing null or undefined to the month and year parameter.

month parameter accepts: null|undefined, number, or string eg 'July'

year parameter accepts: null|undefined, number 2 or 4 digit, string eg '19' or '2019' also 'last', 'this', 'next'

returns Date object,Array[Date object...], or Array[Array[Date object...]...]

This has been tested and should cover most situations...

Solution 3:

Well, it's been over 8 years since I asked this question, and it showed up at the top result on Google for 'The first Tuesday of every month'. The original project is dead now, but I've gained more experience, I feel better placed to provide an answer.

First thing to note, is the original question wasn't obvious, and the title was just as ambiguous. The original goal, was to get the next occurrence of a first Tuesday of the month, so could be the current month, or next month depending on where you are in the month.

Because of the ambiguity in the question, I have tried to cover for those differences in interpretation in the answer.

My first function, is to get the occurrence of a specific day of the week for a given month and year. Thank you to @Amadan in the comments on one of the answers.

functionGetFirstDayOfMonth(dayOfTheWeek, month, year){
    const date = new Date(year, month, 1);
    date.setDate(date.getDate() + ((7 + dayOfTheWeek) - date.getDay()) % 7)
    returndate;
}

The next function, gets the next occurrence of a first specified day of the week given a date.

functionGetFirstNextFirstDayOfTheWeek(currentDate, day){
    const returnValue = GetFirstDayOfMonth(day, currentDate.getMonth(), currentDate.getFullYear());

    if(returnValue.getDate() < currentDate.getDate()){
        returnGetFirstNextFirstDayOfTheWeek(newDate(currentDate.getFullYear(), currentDate.getMonth() + 1), day);
    }

    return returnValue;
}

So to achieve the original question I can run the following example

const tuesday = 2;

functionGetFirstNextFirstTuesday(){
    returnGetFirstNextFirstDayOfTheWeek(newDate(), tuesday);
}

To achieve getting the first Tuesday of a Month

const tuesday = 2;

functionGetFirstTuesday(month, year){
    returnGetFirstDayOfMonth(tuesday, month, year);
}

And to finish getting all the first Tuesdays of a given year.

const tuesday = 2;

functionGetFirstTuesdayOfEveryMonth(year){
    const dates = [];
    for (let index = 0; index < 12; index++) {
        dates.push(GetFirstDayOfMonth(tuesday, index, year));    
    }
    return dates;
}

functionGetFirstDayOfMonth(dayOfTheWeek, month, year){
    // Get the first day of the monthconst date = newDate(year, month, 1);
    // Set the date based on the day of the week. 
    date.setDate(date.getDate() + ((7 + dayOfTheWeek) - date.getDay()) % 7)
    return date;
}

functionGetFirstNextFirstDayOfTheWeek(currentDate, day){
    const returnValue = GetFirstDayOfMonth(day, currentDate.getMonth(), currentDate.getFullYear());

    if(returnValue.getDate() < currentDate.getDate()){
        returnGetFirstNextFirstDayOfTheWeek(newDate(currentDate.getFullYear(), currentDate.getMonth() + 1), day);
    }

    return returnValue;
}

const tuesday = 2;

functionGetFirstTuesday(month, year){
    returnGetFirstDayOfMonth(tuesday, month, year);
}

functionGetFirstNextFirstTuesday(){
    returnGetFirstNextFirstDayOfTheWeek(newDate(), tuesday);
}


functionGetFirstTuesdayOfEveryMonth(year){
    const dates = [];
    for (let index = 0; index < 12; index++) {
        dates.push(GetFirstDayOfMonth(tuesday, index, year));    
    }
    return dates;
}



console.log(GetFirstNextFirstTuesday());
console.log(GetFirstTuesday(09, 2021));
console.log(GetFirstTuesdayOfEveryMonth(2022));

Hopefully, this can help anyone who may seem to stubble on this old post, and thank you to the people that did answer.

Post a Comment for "First Tuesday Of Every Month"