To find the first day of the week for a given date using DateTime in PHP, you can use the modify()
function along with the format()
function. Here's an example:
$date = new DateTime("2022-05-15"); // Your desired date
$dayOfWeek = $date->format('w'); // Get the numeric representation of the week day (0-6, where 0 is Sunday)
$firstDayOfWeek = $date->modify("-$dayOfWeek days")->format('Y-m-d'); // Subtract the numeric representation of the week day from the current date to get the first day of the week
echo $firstDayOfWeek; // Output the first day of the week
In this example, we create a new DateTime
object with the desired date. We then use the format()
method with the 'w'
parameter to get the numeric representation of the week day for that date (0-6, where 0 is Sunday and 6 is Saturday).
Next, we modify the date by subtracting the numeric representation of the week day ($dayOfWeek
) from the current date using the modify()
function. This essentially moves the date back to the first day of the week.
Finally, we use the format()
method again to convert the modified date into the desired format ('Y-m-d'
in this example) and output the first day of the week.