javascriptvue.jsdateelement-plus

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


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