skip to Main Content

As the title says, I’d like to get in PHP last week’s Saturday date and current week’s Saturday date with the constraint of a week starting with Saturday instead of Monday.

I first used strtotime('saturday last week') and strtotime('saturday this week') or new DateTime("saturday last week") and new DateTime("saturday this week") but it obviously doesn’t give the expected result as the week starts with Monday.

So for example, if today is 2024-03-04, the result should be :

  • last Saturday: 2024-02-24
  • this Saturday: 2024-03-02

What would be the simplest way to do that?

2

Answers


  1. If I got it correctly, you can use DateTime class along with modify function to find the desired Saturday dates. So logically it should be:

    // Get last week's Saturday date.
    $lastSaturday = new DateTime('last saturday');
    $lastSaturday->modify('-1 week'); // Adjust for week starting on Saturday.
    echo 'Last Saturday: ' . $lastSaturday->format('Y-m-d') . PHP_EOL;
    
    // Get this week's Saturday date.
    $thisSaturday = new DateTime('saturday this week');
    echo 'This Saturday: ' . $thisSaturday->format('Y-m-d') . PHP_EOL;
    

    By adjusting the date for last Saturday by subtracting a week, you align it with the week starting on Saturday.

    Login or Signup to reply.
  2. I’m not sure if I understand your question correctly. In your example you said

    if today is 2024-03-04, the result should be :
    last Saturday: 2024-02-24
    this Saturday: 2024-03-02

    But it sounds you are trying to get only the last Saturday.

    To get last Saturday you can use this code: (Test here)

    function lastWeekSaturday(int $timestamp){
        $enteredDayOfWeek = date("l",$timestamp); // get week day name
        if( $enteredDayOfWeek == 'Saturday' ){
            $lastWeekSaturday = strtotime('1 saturday ago', $timestamp);
        }else{
            $lastWeekSaturday = strtotime('2 saturday ago', $timestamp);
        }
        
        return date('Y-m-d',$lastWeekSaturday);
    }
    
    echo lastWeekSaturday(time()) ; // prints the last saturday date
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search