How can I retrieve all dates within a week based on a specified week number and year in JavaScript?

Is there a way to retrieve all weekdays (Monday through Friday) in a week based on the given week number?

Here is an example of the input:

var weekNumber = "week + " " + year"; //"35 2020"

The desired output should look like this:

var weekArray = ["2020-08-24", "2020-08-25", "2020-08-26", "2020-08-27", "2020-08-28"];

Answer №1

Here's a demonstration expanding on the concept presented in this Stack Overflow post about calculating date from week number using JavaScript

Start by finding the first date of the week, then generate an array of 7 elements with each element representing a day in that week.

If the day exceeds the total days in the month, increment the month and reset the day to 1.

function getISOWeek(w, y) {
    var simple = new Date(y, 0, 1 + (w - 1) * 7);
    var dow = simple.getDay();
    var ISOweekStart = simple;
    if (dow <= 4)
        ISOweekStart.setDate(simple.getDate() - simple.getDay() + 1);
    else
        ISOweekStart.setDate(simple.getDate() + 8 - simple.getDay());
    const temp = {
      d: ISOweekStart.getDate(),
      m: ISOweekStart.getMonth(),
      y: ISOweekStart.getFullYear(),
    }
    
    const numDaysInMonth = new Date(temp.y, temp.m + 1, 0).getDate()
    
    return Array.from({length: 7}, _ => {
      if (temp.d > numDaysInMonth){
        temp.m +=1;
        temp.d = 1;
      }      
      return new Date(temp.y, temp.m, temp.d++).toUTCString()
    });
}

const weekNumber = "53 2020";

const weekYearArr = weekNumber.split(" ").map(n => parseInt(n))

const weekOut = getISOWeek(...weekYearArr) 

console.log(weekOut);

Input: "35 2020"

Output:

[
  "Sun, 23 Aug 2020 22:00:00 GMT",
  "Mon, 24 Aug 2020 22:00:00 GMT",
  "Tue, 25 Aug 2020 22:00:00 GMT",
  "Wed, 26 Aug 2020 22:00:00 GMT",
  "Thu, 27 Aug 2020 22:00:00 GMT",
  "Fri, 28 Aug 2020 22:00:00 GMT",
  "Sat, 29 Aug 2020 22:00:00 GMT"
]

input : "36 2020"

output:

[
  "Sun, 30 Aug 2020 22:00:00 GMT",
  "Mon, 31 Aug 2020 22:00:00 GMT",
  "Tue, 01 Sep 2020 22:00:00 GMT",
  "Wed, 02 Sep 2020 22:00:00 GMT",
  "Thu, 03 Sep 2020 22:00:00 GMT",
  "Fri, 04 Sep 2020 22:00:00 GMT",
  "Sat, 05 Sep 2020 22:00:00 GMT"
]

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 it time to initialize the document with a specific parameter?

Can someone please explain the purpose of this code snippet to me? $(function($) { $.supermodal(); }); I understand that it's similar to waiting for the document to finish loading before running supermodal. However, I'm confused about the 2n ...

Is there a way to show output on render rather than using console.log in node.js?

I have successfully sorted the objects as shown in the link below. My next challenge is to integrate the sorted object into my render function rather than just using console.log(). I'm uncertain if converting it back into an object is the right appro ...

Tips for Adding or Deleting 2 Rows in a Table

When the basket icon on the right is clicked, I want to remove both the current <tr> and the yellow one as well. Check out this screenshot: This is the HTML code for the two rows that need to be deleted with a click: <tr> <t ...

How to modify a single entry in a MongoDB database with the help of Node.js and

How do I update a specific record by _id in a MongoDB collection? A recent UPDATE: After making some changes to the code, I now encounter a 500 internal server error. Any suggestions on resolving this issue would be greatly appreciated. "_id ...

How can I create a popup window that meets standards using XHTML and Javascript?

As I adhere to writing standards compliant XHTML Strict 1.0, I refrain from using the HTML "target" attribute on anchor elements. I have come across 2 distinct methods involving Javascript: One approach involves locating all links with rel='exter ...

AngularJS is not a fan of using the anchor tag

Issue: The code I am currently using is functioning properly: <div style="margin-top: 5pt;"> <a href="{{e.DocURL}}" target="_blank"> <button class="btn btn-primary" id="showDocs" ng-show="e. ...

Interacting with my Rails API through JavaScript requests

Exploring the world of Rails and diving into creating a basic rails-api. Currently facing an issue while trying to incorporate user addition to my model using a JavaScript request... Let's take a look at my HTML file named add-user.html: <script ...

I am experiencing difficulties in creating the app while following the Ember.js 2.4 "Introduction" tutorial

Currently delving into the realm of Ember.js, I decided to start by skimming through installation tutorials using npm. Following that, I attempted a brief Getting Started tutorial provided on their website. Without much exploration, I diligently executed e ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

Tips for transferring information between components using observables and showcasing the data in a different HTML template within Angular

Hey there! I'm currently facing a challenge where I need to pass an object from the 1st Component to the 2nd Component upon a click event. My approach involves using a data service with set and get functions: Data Service @Injectable({ providedIn: ...

Transmitting solely the updated information from the database

I am working on a table that is populated with data from the server using ajax. The table has columns A, B, C, and D where C and D are editable by the user. After the user makes changes to the data in the table, I need to capture only the lines that have b ...

index.ts import statement results in undefined value being returned

I have a simple file structure set up like this: src index.ts services my-service.ts In index.ts, I have the following code: export const a = 3 And in my-service.ts, I use the following import statement: import { a } from '../index' consol ...

Java program to extract substring from related strings

Within my JavaScript code, I am dealing with two string arrays: var names = [name1, name2, name3, name4]; var values = [value1, value2, value3, value4]; To send these array values to the backend, I have created strings as shown below: var nameString = " ...

Expanding Javascript Array Objects with Dynamic Parameters based on Conditions

I'm trying to dynamically add a parameter to the array object url based on a function's value. Unfortunately, my attempts so far have been unsuccessful. var change_lookup_number = function() { var type = document.getElementById('type_num ...

The request to sign up at 'https://identitytoolkit.googleapis.com/v1/accounts:/signUp? from the origin 'http://localhost:8080' has been denied

My attempt to create a new user in Firebase using Axios in Vue.js is resulting in an error message regarding CORS policy. The specific error states: "Access to XMLHttpRequest at 'https://identitytoolkit.googleapis.com/v1/accounts:/signUp?key=AIzaSyDvZ ...

Angular: Assigning a variable

Trying to implement the rickshaw module for graph creation in my application, I carefully followed the instructions provided here, but unfortunately, it did not work out as expected. Below is a snippet of my HTML: <rickshaw rickshaw-options ...

Establish a cookie using the PHP session's username

I have successfully implemented a general cookie for a one-time use scenario. However, I now need to create a cookie based on the username so that a message is displayed only once per user. My approach involves setting up a PHP session for the username ass ...

Updating data dynamically in pug front end using Axios call response

I am currently working on implementing a search form along with an endpoint to retrieve the results. Once I receive the response, I want to dynamically add a div element to my pug/jade file to notify the user whether an order has been found or not. Here i ...

Is it possible to launch an Electron application by clicking a run button in the VSCode

I'm new to using VSCode and am currently working on an HTML5 app with Electron. I'm finding it cumbersome to switch between windows and enter a command each time I want to test my application. Is there a way to configure VSCode to run my Electron ...

Converting a List of Maps from Immutable.js into a List of Lists and utilizing it as the dataset for Google Charts

I am currently working on implementing the Google Charts library to visualize some time series data. Right now, I have dummy data stored in a separate file from my application. In this file, I have an Immutable List structured like this: le ...