Is there a way to determine the last full week of any given month? For example, I need to find the Wednesday of the last full week in April each year. Here is the desired output: April 24, 2019, April 22, 2020, April 28, 2021, April 27, 2022, and so on.
var today = new Date();
var y = today.getFullYear();
var d = new Date(y, 3, 0);
var NumWks = Math.floor(d.getDate() - 1 / 7) + 1;
I have managed to calculate the number of weeks in April (in the above example), which results in 5. However, since the 5th week is not complete, I need to identify the 4th week. How can I test if the last week is a full week and, if not, use the previous week?
var nth = //this is the missing piece - how to find the last full week in April.
After determining the nth full week, I can continue with the formula provided:
var Wed = 3;
var FirstWedofApril = new Date(y, 3, 1 + (Wed - new Date(y, 3, 1).getDay() + 7) % 7);
var LastWedOfFullWeek = new Date(FirstWedofApril.getFullYear(), FirstWedofApril.getMonth(), FirstWedofApril.getDate() + (nth - 1) * 7);
The formula was obtained from Date Hacks.
EDIT FINAL CODE The for loop is used to check the next 10 years.
var today = new Date();
var y = today.getFullYear();
for (i = 0; i < 10; i++) {
var yr = y + i;
var apr = 3;
var wed = 3;
//Get first Wednesday in April
var FirstWed = new Date(yr, apr, 1 + (wed - new Date(yr, apr, 1).getDay() + 7) % 7);
//Get Number of weeks in April
var d = new Date(yr, apr, 0);
var NumWks = Math.floor((d.getDate() - 1) / 7) + 1;
//Get Last Date in April
var lastDateApr = new Date(yr, apr + 1, 1);
lastDateApr.setDate(lastDateApr.getDate() -1 );
//Get Last Date in April - Day of Week
var dow = lastDateApr.getDay();
//Get Wednesday of last full week in April
if (dow == 7) {
var lastWed = new Date(FirstWed.getFullYear(), FirstWed.getMonth(), FirstWed.getDate() + (NumWks - 1) * 7);
} else {
var lastFullWk = NumWks - 1;
var lastWed = new Date(FirstWed.getFullYear(), FirstWed.getMonth(), FirstWed.getDate() + (lastFullWk - 1) * 7);
}
text = text + yr + ": " + lastWed + '<br>';
}
document.getElementById("WedAprLastFW").innerHTML = text;
}
Below are the outputs:
- 2019: Wed Apr 24 2019 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2020: Wed Apr 22 2020 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2021: Wed Apr 28 2021 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2022: Wed Apr 27 2022 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2023: Wed Apr 26 2023 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2024: Wed Apr 24 2024 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2025: Wed Apr 23 2025 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2026: Wed Apr 22 2026 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2027: Wed Apr 28 2027 00:00:00 GMT-0700 (Pacific Daylight Time)
- 2028: Wed Apr 26 2028 00:00:00 GMT-0700 (Pacific Daylight Time)