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

Guide on extracting just the key and its value from a Filter expression in a DynamoDB Query using Typescript

Presented here is a filter expression and Key Condition. The specific set of conditions are as follows: {"Age":{"eq":3},"Sex":{"eq":"MALE"}} const params: QueryCommandInput = { TableName: my_tab ...

My React application did not display properly after deploying it on GitHub Pages

I attempted to deploy my React app on GitHub Pages, but unfortunately it did not work as expected. When I tried to access the link, all I got was a blank page. Can anyone help me with a solution? Your assistance is much appreciated! Here's a snippet ...

Extracting raw data from the dojo.xhrGet request

When working with a JSP and servlet, I encountered an issue. In the JSP, I make an ajax call to the servlet which in turn calls a REST API to fetch JSON data. Using json.serialize(true);, I format the JSON data in the servlet before sending it to the front ...

How can the date format in a CSV file be modified using Python?

Looking to convert the date format from 30-Jan-02 to 30.Jan.2002 when it appears in the second position within a CSV file using Python. I've made several attempts, but I'm getting caught up with compatibility between strings and bytes. import os ...

Discovering the specific type of an object property in TypeScript

I am currently working on implementing a lookup type within an object. Imagine my object structure as follows: class PersonList { persons = { john: 'description of john', bob: 'description of bob' } } I want to create a ge ...

Rotate each row of the table in sequence with a pause between each flip

I have a table with 3 columns and 10 rows. I would like to flip each row one by one, where each row contains data on both the front and back sides. The flipping animation should be similar to the example provided in this link, but the flipping should sta ...

JavaScript Functions for Beginners

I'm currently facing some challenges with transferring the scripts and HTML content from the calendar on refdesk.com. My task involves moving the JavaScript to a separate stylesheet and utilizing those functions to replicate the calendar on an HTML pa ...

Tips for showing form values in pop-up boxes based on their unique identifiers

I am experiencing an issue with displaying posted values in a pop-up box. Specifically, when I click on "Book now", it only shows one set of id values for all entries. For example, if I click on the 1st row's "Book now" button, it displays the values ...

Understanding the process of retrieving a data value from HTML in an AngularJS directive

I'm a beginner with Angular and I'm trying to pass some data to my angular directive from the template. <div class="col-md-6" approver-picker="partner.approverPlan.data" data-pickerType="PLAN"></div> I h ...

The function toJson() does not exist for the specified stdClass object

After following a tutorial on implementing websockets in Laravel to create a live commenting system, I encountered an error that I cannot figure out. Even though I followed the code exactly as demonstrated in the video, this error persists. Does anyone hav ...

Implementing data waiting strategy in Vue component using TypeScript for rendering

When working with the first component, I encountered a scenario where I needed to open a new page using the router functionality: In Component_1.vue: let route = this.$router.resolve({ name: 'Schedule', params : { id: (this.schedule[0].schedule ...

What is the best way to retrieve a nested data type?

I am working with an interface named IFoo interface IFoo { name: string; version: number; init: (arg1: string, arg2: number) => Promise<string[]>; } I am interested in the type of init. Is there a way to extract it so that I can use this i ...

Managing two separate instances with swiper.js

Currently, I have set up two instances of swiper.js and I am looking to scroll both while interacting with just one of them. Update: My primary objective is to replicate the core functionality seen on the swiper homepage. Update 2: I came across this lin ...

Utilizing a form on numerous occasions prior to its submission

As a newcomer to JavaScript, I am exploring the best approach for a specific task. The task involves a form with checkboxes representing different music styles and a selector for names of people. The goal is to allow users to select music styles for mult ...

Issue occurring while trying to select an item from the dynamically generated options using AJAX

A JavaScript function is used in this code to select a specific option, with the option value being specified within a hidden element: $("select").each(function() { var id = $(this).attr('id'); var source = 'input:hidden[na ...

Why won't my AngularJS checkbox stay checked?

In my application, I have the following code: <input type="checkbox" ng-checked="vm.eduToEdit.test" /> {{vm.eduToEdit.test}} <input type="checkbox" ng-model="vm.eduToEdit.test"> The value of vm.eduToEdit.test is displaying t ...

Angular 11 Working with template-driven model within a directive

My currency directive in Angular 8.2 formats currency fields for users by using the following code: <input [(ngModel)]="currentEmployment.monthlyIncome" currency> @Directive({ selector: '[ngModel][currency]', providers: [Curr ...

Error: The OrbitControls function is not recognized in THREE.JS

const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const controls = new OrbitControls(camera); camera.position.set(200, 0, 0); controls.update(); const geometry = new THREE.S ...

Encapsulating functions with multiple definitions in Typescript

Struggling with wrapping a function that can have multiple return types based on input parameters in Typescript. Imagine wanting a function to return ReturnA for VariantEnum.a and ReturnB for VariantEnum.b. Consider this implementation of sampleFunction: ...

assigned to a variable and accessed in a different route

Why does the "res.username" variable return as undefined in the second route even though my user needs to login before accessing any route? router.post('/login', passport.authenticate('local'), function(req, res) { res.username = r ...