1

enter image description here

Today is April 7th, and the closest the beginning date of the week is April 5.

How do I programmatically getting the startDay of the current week using PHP ?


I've tried

$dateStartWeek = date('N', strptime('%m-%d-%g', $dateString));
dd($dateStartWeek);

and tried

    function getFirstDayOfWeek(DateTime $date, $firstDay = 0) {
        $offset = 7 - $firstDay;
        $ret = clone $date;
        $ret->modify(-(($date->format('w') + $offset) % 7) . 'days');
        return $ret;
    }


    $dateStartWeek = getFirstDayOfWeek(date("y-m-d"));
code-8
  • 54,650
  • 106
  • 352
  • 604

2 Answers2

1

Use the relative date format sunday last week

echo date("j F", strtotime('sunday last week'));

5 April

SandBox

0stone0
  • 34,288
  • 4
  • 39
  • 64
0

Use relative datetime formats - https://www.php.net/manual/en/datetime.formats.relative.php

In your case:

new \DateTImeImmutable('this week')
  • I got this `DateTimeImmutable @1586187250 {#437 date: 2020-04-06 11:34:10.237062 America/New_York (-04:00) }`, The answer is `5`, since Apirl 5 is the start date. – code-8 Apr 07 '20 at 15:34
  • Ok, in case you start your weeks on Sunday, do `new \DateTImeImmutable('this week - 1 day')` – Patrick Kusebauch Apr 07 '20 at 15:37