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 period from last week's Monday to last week's Sunday

How to get period from last week’s Monday to last week’s Sunday as a date using JavaScript

I tried to find information in different sources, but did not find an answer, I hope they will help me here

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

>Solution :

Assuming timezone is not an issue, you can make use of the Date.prototype.setDate() to first get an anchor to last week, then use getDay to know which day you are in, offset that by your anchor and you can obtain the Monday and Sunday:

const today = new Date();

const oneWeekAgo = new Date(+today);
oneWeekAgo.setDate(today.getDate() - 7);
oneWeekAgo.setHours(0, 0, 0, 0); // Let's also set it to 12am to be exact

const daySinceMonday = (oneWeekAgo.getDay() - 1 + 7) % 7

const monday = new Date(+oneWeekAgo);
monday.setDate(oneWeekAgo.getDate() - daySinceMonday);

const sunday = new Date(+oneWeekAgo);
sunday.setDate(monday.getDate() + 6);

console.log(monday, sunday);
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