Retrieve the specific day of the previous complete week within a designated month using JavaScript

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)

Answer №1

Calculate the final day of the month by determining the current day and subtracting specific days based on the weekday:

Sunday -3 Monday -4 Tuesday -5 Wednesday -6 Thursday -7 Friday -8 Saturday -9

This method will give you the last Thursday in a complete week within the month.

Edit: Additionally, to ensure that the week is complete, check if the last day falls on a Sunday or Saturday, depending on your location.

Edit2: To find the last day of the month, simply find the first day of the following month (which is easy because it's the first) and then subtract one day.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

Cease the execution of processes once a Promise has been rejected

My current code is functioning correctly, but I am facing an issue where if an error occurs, I want it to halt all other promises in the chain. Specifically, when chi.getCommand(val1, val2) returns a reject and triggers the exception catch block, I need to ...

What is the process of converting code to JavaScript and React?

There are two methods defined as shown below. const handleClick = React.useMemo(() => !isRunning ? (items: string | string[]) => { if(Array.isArray(items)){ startRun({ items: items }); } else ...

How can we verify that console.log has been called with a specific subset of expected values using Jest?

I am currently experimenting with a function that adds logging and timing functionality to any function passed to it. However, I am facing a challenge when trying to test the timing aspect of it. Here are my functions: //utils.js export const util_sum = ( ...

Struggling to make the grunt.js task for postcss with autoprefixer function properly

I am currently facing issues with using postcss in conjunction with autoprefixer-core. Even though the css is being generated correctly, autoprefixer doesn't seem to be applying any prefixes. I have already installed postcss and autoprefixer via NPM ...

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

What is the best way to manage div visibility and sorting based on selections made in a select box?

Explaining this might get a bit confusing, but I'll do my best. In my setup, I have two select boxes and multiple divs with two classes each. Here is what I am trying to achieve: When an option is selected, only the divs with that class should be ...

Finding the way to locate obsolete or deprecated packages in NPM versions

Is there a way to easily identify outdated deep dependencies in the local node_modules folder, separate from the top-level packages? After running the command: npm install with this content in my package.json: "dependencies": { "bluebi ...

Retrieve information from Angular service's HTTP response

Calling all Angular/Javascript aficionados! I need some help with a service that makes API calls to fetch data: app.service("GetDivision", ["$http", function($http){ this.division = function(divisionNumber){ $http.post("/api/division", {division:di ...

What steps must be taken to display a div element upon clicking an object or entity within an Aframe scene?

Experiencing some coding issues that I could use help with. As a newcomer to Javascript, I might be making a beginner's error here. My goal is for the red tree on the globe in my example to trigger a red div box when clicked. Despite my efforts, I kee ...

Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area. I am curious about dynamically adding a getter method to a Prototy ...

Tips for resizing mesh along the global axis

Have you ever used an online 3D editor that allows you to manipulate individual meshes by moving, scaling, and rotating them? This editor utilizes custom transform controls inspired by the TransformControls code from three.js. Here is a snippet of code fro ...

Configuring webpack for live reloading and Hot Module Replacement on static pages

The title of this post may not be very clear, but I appreciate your patience. I am currently in the process of setting up React for an older Rails application that uses static ERBs. Due to the size of the project, I am gradually transitioning towards a Si ...

What measures can be taken to block Javascript from retrieving PHP cookie information?

(Extracted from an interview) Identify the correct answers from the list below: Implement the httponly parameter when creating the cookie The user needs to disable Javascript support This setting is related to cookies in the browser Restrict access to t ...

Tips for transforming a date into a time ago representation

Can someone help me with converting a date field into a "timeago" format using jquery.timeago.js? $("time.timeago").timeago(); var userSpan = document.createElement("span"); userSpan.setAttribute("class", "text-muted"); userSpan.appendChild(document.crea ...

I'm curious about what exactly happens when the NextJS Link component is triggered and how we can effectively capture and respond

As I was developing a simple navbar that uses a JSON data to dynamically generate its links, I encountered the need to visually persist the active link/route. To achieve this, I experimented with two different implementations: Initial approach: In the Me ...

How can I verify an element's attribute while employing Event Delegation?

Is there a method to determine if a particular element has been activated using Event Delegation, based on its attribute, class, or ID? <ul> <li><button>Make the first paragraph appear</button></li> <li><butto ...

Programmatically switch between show and hide using Angular Material

Is there a way to programmatically toggle between displaying and hiding attributes by clicking a button? For example, I have a card that includes both a map and a list view. Normally, these are shown side by side. However, on mobile devices, the list view& ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...