Home > Back-end >  Get the past week 7 day period from a given date in Javascript
Get the past week 7 day period from a given date in Javascript

Time:04-17

I am trying to get the date range of the past Wednesday to past Tuesday(7 days) from today's date. Say the current date is 2022-05-01(May 1st), I am expecting the result to be the past Tuesday(end date) to Past Wednesday (start date = Past Tuesday -7 days) i.e 20 April 2022 to 26 April 2022

function getStartAndEndDates () {
    var now = new Date('2022-05-01'); //May 1st 2022
    var day = now.getDay();
    var diff = (day <= 2) ? (7 - 2   day ) : (day - 2);
    var PastTuesday = new Date();
    var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));
    console.log('End date is', PastTuesday.toISOString());
    PastWednesday.setDate(PastTuesday.getDate() - 6);
    console.log('Start Date is',PastWednesday.toISOString());
    return[PastWednesday,PastTuesday];
 
}
Output obtained is:
End date is 2022-03-27T19:25:35.726Z //here month is set to March
Start Date is 2022-03-21T19:25:35.726Z

Expected Result is
End date is 2022-04-26T19:25:35.726Z // month is supposed to be April
Start Date is 2022-04-20T19:25:35.726Z

How can I change the code to get the expected result?

CodePudding user response:

You should do something like

function getLastWeek(date) {
      var today = new Date(date);
      var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
      return lastWeek;
    }
    // Your DATE
    date = '2022-05-01'
    //
    var lastWeek = getLastWeek(date);
    var lastWeekMonth = lastWeek.getMonth()   1;
    var lastWeekDay = lastWeek.getDate();
    var lastWeekYear = lastWeek.getFullYear();

    var lastWeekDisplay = lastWeekMonth   "/"   lastWeekDay   "/"   lastWeekYear;

    console.log(lastWeekDisplay);

CodePudding user response:

In your code:

var now = new Date('2022-05-01'); //May 1st 2022

Dates in the format YYYY-MM-DD are parsed as UTC, so the above will create a date object representing 2022-05-01T00:00:00Z.

var day = now.getDay();

This will return the local day number. For users with a zero or positive offset, it will return 0 (Sunday) but for users with a negative offset, it will return 6 (Saturday) because their local date is still the previous day.

var diff = (day <= 2) ? (7 - 2   day ) : (day - 2);

Given day is 0 (for me), the above sets diff to 5.

var PastTuesday = new Date();

This creates a date for "now", which for me is 17 April.

var PastWednesday = new Date(PastTuesday.setDate(now.getDate() - diff));

In the above, now.getDate returns 1, and 1 - 5 is -4, so it sets the date for PastTuesday to -4. Now PastTuesday is in April, so it is set to 4 days prior to the start of April, i.e. 27 March.

Note that this adjusts PastTuesday and creates a copy for PastWednesday at the same time.

console.log('End date is', PastTuesday.toISOString());

Shows the equivalent UTC date and time, with the time representing the time that the code was run.

PastWednesday.setDate(PastTuesday.getDate() - 6);

Sets PastWednesday to 6 days prior to PastTuesday.

Anyhow, what is required is to do everything either as UTC or local, don't mix the two.

Sticking to code as closely as possible to the original and assuming a timestamp in YYYY-MM-DD format is parsed to the function, consider the following, which does everything as local:

// Parse timestamp in YYYY-MM-DD format as local
function parseISOLocal(s = new Date().toLocaleDateString('en-CA')) {
  let [y, m, d] = s.split(/\D/);
  return new Date(y, m-1, d);
}

// Get week Wed to Tue prior to passed date
function getStartAndEndDates (date) {

    // Parse timestamp as local
    var pastTuesday = parseISOLocal(date);
    
    // Adjust pastTuesday to previous Tuesday
    var day = pastTuesday.getDay();
    var diff = (day <= 2) ? (7 - 2   day ) : (day - 2);
    var pastWednesday = new Date(pastTuesday.setDate(pastTuesday.getDate() - diff));
    console.log('End date is', pastTuesday.toDateString());
    
    // Adjust pastWednesday to previous Wednesday
    pastWednesday.setDate(pastTuesday.getDate() - 6);
    console.log('Start Date is',pastWednesday.toDateString());
    
    return [pastWednesday, pastTuesday]; 
}

// Sunday 1 May 2022
console.log(getStartAndEndDates('2022-05-01').map(d => d.toDateString()));
// Current date
console.log(getStartAndEndDates().map(d => d.toDateString()));

  • Related