skip to Main Content

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

2

Answers


  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);
    Login or Signup to reply.
  2. First let us find the day of today.

    const today = new Date(); 
    

    Then we’ll 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 we can 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, we just subtract 6 days from that date.

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

    Then we can 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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search