[Vuejs]-How to get period from last week's Monday to last week's Sunday

1👍

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);

3👍

First find the day of today.

const today = new Date(); 

Then find find what day it is.

const dayOfWeek = today.getDay()

The above will return the day of the week where Sunday = 0 and Saturday = 6.

With this go back until last Sunday by subtracting the day of the week from the day.

const lastSunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek);

And then to get the last monday, subtract 6 days from that date.

const lastMonday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek - 6);

Then convert the dates to strings

const lastMondayStr = lastMonday.toISOString().slice(0, 10);
const lastSundayStr = lastSunday.toISOString().slice(0, 10);

In all it would look like this

const today = new Date(); 
const dayOfWeek = today.getDay()
const lastSunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek);
const lastMonday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - dayOfWeek - 6);

const lastMondayStr = lastMonday.toISOString().slice(0, 10);
const lastSundayStr = lastSunday.toISOString().slice(0, 10); 

console.log('Period ' + lastMondayStr + ' - ' + lastSundayStr)

Edit: Adjusted wording to sound less smarmy after some feedback from @RobG

Leave a comment