PHP for finding the first day of the week for a given date
PHP Code:
<?php
function getFirstDayOfWeek($dateStr) {
$date = new DateTime($dateStr);
$dayOfWeek = $date->format('w');
$daysToSubtract = $dayOfWeek - 1;
$firstDayOfWeek = $date->sub(new DateInterval('P' . $daysToSubtract . 'D'));
return $firstDayOfWeek->format('Y-m-d');
}
// Example usage
$dateStr = '2023-03-08';
$firstDayOfWeek = getFirstDayOfWeek($dateStr);
echo $firstDayOfWeek; // Output: 2023-03-06
?>
Explanation:
-
Create a DateTime object for the given date: Use
DateTime::createFromFormat()
orDateTime::__construct()
to create aDateTime
object from the given date string. -
Get the day of the week: Use the
format()
method to get the day of the week (0 for Sunday, 1 for Monday, etc.) as a number using the format string ‘w’. -
Calculate the number of days to subtract: Determine how many days need to be subtracted from the current date to get to the first day of the week. This is done by subtracting the day of the week from 1.
-
Subtract the calculated days: Use the
sub()
method to subtract the calculated number of days from theDateTime
object. -
Format and return the first day of the week: Use the
format()
method again to format the resultingDateTime
object as a string in the desired format (e.g., ‘Y-m-d’).