Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get current week date in javascript?

I have a problem getting the current week date in javascript. I wrote the following code to get the current week’s date, It was working well but it seems it sometimes returns the next week’s date. I could not understand where is the problem.
any help would be appreciated.

This is my code:

let curr = new Date();
let week = [];

for (let i = 1; i <= 7; i++) {
  let first = curr.getDate() - curr.getDay() + i;
  let day = new Date(curr.setDate(first)).toISOString().slice(0, 10);
  week.push(day);

};
console.log(week)

The output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['2022-06-13', '2022-06-14', '2022-06-15', '2022-06-16', '2022-06-17', '2022-06-18', '2022-06-19']

but today’s date is 6/12/2022, but the above date started from 13/06/2022

Source:
here

>Solution :

If I understand your question correctly, you must take into consideration when current day is sunday to get current week first day (monday).

let curr = new Date();
let week = [];

for (let i = 1; i <= 7; i++) {
  let first = curr.getDate() - curr.getDay() + i;
  
  if (curr.getDay() === 0){
    first = curr.getDate() - 6;
  }
  let day = new     Date(curr.setDate(first)).toISOString().slice(0, 10);
  week.push(day);

};
console.log(week)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading