Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particular week. For instance:

function getDaysOfWeekDates(year: number, month: number, weekNumber: number): Array<Date> {
     //...
}
const days: Date[] = getDaysOfWeekDates(2020, 0, 2) // Second week of January 2020
console.log(days);

/**
 * 2020-01-06T00:00:00.000Z
 * 2020-01-07T00:00:00.000Z
 * 2020-01-08T00:00:00.000Z
 * 2020-01-09T00:00:00.000Z
 * 2020-01-10T00:00:00.000Z
 * 2020-01-11T00:00:00.000Z
 * 2020-01-12T00:00:00.000Z
 */

I have already created a function named getDaysOfWeekDates2 which works similarly, but accepts a year and a week number as parameters (week relative to the year, where each year has 52-53 weeks):

function getDaysOfWeekDates2(year: number, weekNumber: number) {
    const [ startDate ] =  getDateRangeOfWeek(year, weekNumber);

    return new Array(7).fill(null).map((e, index) => {
      
      return new Date(
        startDate.getFullYear(), 
        startDate.getMonth(), 
        startDate.getDate() + index
      );
    });
}
function getDateRangeOfWeek(year: number, weekNumber: number){
    
    const date = new Date(String(year));

    const numOfdaysPastSinceLastMonday = date.getDay() - 1;
    date.setDate(date.getDate() - numOfdaysPastSinceLastMonday);
    date.setDate(date.getDate() + (7 * (weekNumber - getWeekNumber(date))));

    const rangeIsFrom =  new Date(date.getFullYear() + "-" +(date.getMonth() + 1) + "-" + date.getDate());
    date.setDate(date.getDate() + 6);
    const rangeIsTo = new Date(date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + + date.getDate());
    
    return [rangeIsFrom, rangeIsTo];
};
function getWeekNumber(date: Date): number {
    const dateCopy = new Date(date.getTime());

    dateCopy.setHours(0, 0, 0, 0);
    // Thursday in current week decides the year.
    dateCopy.setDate(dateCopy.getDate() + 3 - (dateCopy.getDay() + 6) % 7);
    // January 4 is always in week 1.
    const week1 = new Date(dateCopy.getFullYear(), 0, 4);
    // Adjust to Thursday in week 1 and count number of weeks from date to week1.
    return 1 + Math.round(((dateCopy.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
  }

Any thoughts on how to modify getDaysOfWeekDates? to achieve the desired functionality of getDaysOfWeekDates? Or perhaps create it from scratch using an external library?

Answer №1

In case you prefer Monday to be the first day of the week, and the initial week of a month is determined by the presence of the first Thursday, you can apply a comparable algorithm to the year-week numbering function.

To achieve this, identify the beginning of the specific week required, then iterate 7 times to acquire each day. For example:

/* Retrieve the first day of the specified week in any given month of the year
**
** @param {number|string} year - year for the desired week
** @param {number|string} month - month for the desired week
**         The month number corresponds to the calendar months, where 1 = Jan, 2 = Feb, etc.
** @param {number|string} week - week within the month
**         The first week of the month is identified by the first occurrence of a Thursday
** @returns {Date} date corresponding to the start of the required week on Monday
*/
function getMonthWeek(year, month, week) {
  // Set the date to the 4th of the month
  let d = new Date(year, month - 1, 4);
  // Determine the day number, setting Sunday as 7
  let day = d.getDay() || 7;
  // Adjust to the previous Monday
  d.setDate(d.getDate() - day + 1);
  // Navigate to the required week
  d.setDate(d.getDate() + 7 * (week - 1));
  return d;
}

// Obtain an array of dates pertaining to a specified week within a month of a given year
function getWeekDates(year, month, week) {
  let d = getMonthWeek(year, month, week);
  for (var i=0, arr=[]; i<7; i++) {

    // Collection of date strings
    arr.push(d.toDateString());

    // To obtain an array of Date objects, replace the above line with
    // arr.push(new Date(d));

    // Progress to the next date
    d.setDate(d.getDate() + 1);
  }
  return arr;
}

// Display the week dates for week 1 of January 2020 - starting in the prior year
console.log(getWeekDates(2020, 1, 1));
// Exhibit the week dates for week 5 of January 2020 - considering a month with 5 weeks
console.log(getWeekDates(2020, 1, 5));
// Showcase the week dates for week 1 of October 2020 - commencing with a Thursday
console.log(getWeekDates(2020, 10, 1));
// Present the week dates for week 1 of November 2020 - beginning on a Sunday
console.log(getWeekDates(2020, 11, 1));

If uncertain whether an array of Date objects or strings is preferred, both versions are provided in the comments.

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

Is there a way to toggle the slide effect of one 'div' without affecting another one?

Hey everyone! I am new to jquery and currently working on a project with two div elements that are slidetoggled. The issue I am facing is that when I open or close one div, the other div also moves along with it. I understand what is happening in the back ...

nodemon and ts-node not working as expected, failing to automatically recompile

I have been working on creating a REST API using express+ts-node. Following various online tutorials, I managed to set everything up and when I run the app using npm run dev, it works perfectly fine. However, I am facing an issue where it is not automatica ...

react: implement custom context menu on videojs

Can someone assist me with adding a quality selector and disabling the right-click option in a webpage that uses videojs? I am unsure about using plugins, as there were no examples provided in react. Any guidance would be appreciated. VideoPlayer.js impor ...

Preventing the build-up of opacity animations in jQuery: Tips and tricks

-I have two division tags in my code. <div id="div1">Hover over me to show Div2</div> <div id="div2">Div2</div> -I used CSS to set the opacity of div2 to 0. -My goal is for div2's opacity to change from 0 to 1 when hovered o ...

The Environment variable in React Native is not functioning when utilizing TypeScript

After installing the react-native-dotenv library, I followed the instructions outlined in the TypeScript guide. I then created a .env file with the following contents: MARVEL_API = <url> MARVEL_PUBLIC_KEY = <public-key> MARVEL_PRIVATE_KEY = &l ...

Unable to locate the JavaScript/jQuery key

Struggling with a dictionary in JavaScript being passed to a function in Django. Despite the key existing, I'm getting an error saying 'key message not found'. As a newbie in Javascript and JQuery, I must have made a simple mistake somewhere ...

incorporating numerous interconnected javascript files within a single html document

I have a pair of JavaScript files (file1, file2). File1 utilizes a class that is defined in file2. Can I include these files in an HTML document like this: <script type="text/javascript" src="file1.js"></script> <script type="text/javascrip ...

Is the key to achieving optimal client interactions within a client layout, while still maintaining its role as a server component, truly possible?

My current challenge involves managing modals opening and closing with server components instead of client components. In the past, I used to lift the state up to my Layout for client components: export default function Layout({ children }) { const [showP ...

Adjust website content depending on user's authentication status

My goal is to display a logout button when the user is logged in and a login button if they are not. I am using JSON tokens to determine if a user is logged in or not, by checking if the token is null. However, this approach does not seem to be working. Ca ...

Utilizing React to adapt to varying HTML layouts while maintaining consistent component usage

How can I create an App with two different views for mobile and desktop without relying solely on CSS Media Queries? I have been searching for guidance but so far haven't found a solution. Any advice or direction on where to find documentation or oth ...

What is the best way to specify the return type in TypeScript when there is a possibility of multiple types?

I'm currently working on implementing type definitions for an Axios API client but I’m struggling with indicating to the compiler the specific return type that I am expecting. Here is a simplified example: import axios, { AxiosResponse } from "axi ...

Transfer groups between divisions

In my HTML structure, I have two main divs named Group1 and Group2. Each of these group divs contains at least two inner divs, all with the class .grp_item. Currently, the grp_item class is set to display:none, except for one div in each group that has a c ...

Error message: App not defined in Ember App.router

Attempting to set up routing for my app for the first time, but struggling to grasp the logic. I managed to render my templates by adding the following code to my route.js file: import Ember from 'ember'; import config from './config/enviro ...

How can I make the fullcalendar 'moreLink' popover stay open when clicking outside?

Currently, I am working with FullCalendar v6 on nextjs. One built-in feature that caught my attention is the event popover that appears when there are too many events, accessible by clicking "more." However, I am facing a challenge in preventing this pop ...

Building a versatile dropdown menu with ReactJS and creating reusable components

I am currently working on building a dropdown menu following a tutorial, but I have encountered a roadblock. Instead of using the "props" keyword as shown by the instructor in the tutorial, I passed the props directly as arguments without using props dot. ...

Utilizing SVG elements for interactive tooltips

Can the < use > element show the rect tooltip on mouseover in modern browsers? Refer to 15.2.1 The hint element. <svg id="schematic" version="1.2" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol i ...

Creating personalized columns in a BootstrapVue table

I'm having an issue with the b-table component in bootstrap-vue. The array containing my items is structured like this: [{ id: 1, name: "Test", phone: 555-111-666, address: "Some Address", //etc... }] I have a couple of question ...

Utilize Firebase for Playwright to efficiently implement 'State Reuse' and 'Authentication Reuse'

In my testing environment, I want to eliminate the need for repeated login actions in each test run. My approach involves implementing 'Re-use state' and 'Re-use Authentication', but I've encountered a challenge with Firebase using ...

Issue with handling keypress event and click event in Internet Explorer

Below is the HTML code for an input text box and a button: <div id="sender" onKeyUp="keypressed(event);"> Your message: <input type="text" name="msg" size="70" id="msg" /> <button onClick="doWork();">Send</button> </di ...

"Unleashing the power of infinite Ajax requests upon a drop change event in Knock

I am working with Knockout MVC on my current project and encountering an issue. Whenever I try to pass the viewModel when the Drop Down changes, the method call gets invoked multiple times and the alert message "ok" keeps popping up continuously. Can som ...