Tamras Merin
Tamras Merin

Reputation: 159

Get the nth day of last full week in any given month (javascript)

I'm trying to get the Wednesday of the last full week in April each year. Output example: April 24, 2019, April 22, 2020, April 28, 2021, April 27, 2022, etc.

How can I identify the last full week in any given month?

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've only managed to get the number of weeks in April (in above example) (result: 5) but the 5th week is not a complete week so I need the 4th week. I need some kind of test to check if the last week is a full week, if not, use the week before?

var nth = //this is what I need to figure out, the last full week in April.

Once I've managed to get the nth of the full week, i can use the rest of the formula

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);

I got the above formula from Date Hacks

EDIT FINAL CODE The for loop is just to test 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 output:

Upvotes: 2

Views: 229

Answers (1)

Bacon
Bacon

Reputation: 483

get the last day of month, check what day it is, and substract days depending on the weekday

on sunday -3 on monday -4 on tuesday -5 on wednesday -6 on thursday -7 on friday -8 on saturday -9

then you get the last thursday in a full week in the month

edit : also to check if your week is a full week is when the last day is a sunday or saturday, depending on locale

edit2: to get the last day of the month you get the first day of the month after (thats easy because its the first) and substract a day

Upvotes: 3

Related Questions