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:

  1. Create a DateTime object for the given date: Use DateTime::createFromFormat() or DateTime::__construct() to create a DateTime object from the given date string.

  2. 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’.

  3. 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.

  4. Subtract the calculated days: Use the sub() method to subtract the calculated number of days from the DateTime object.

  5. Format and return the first day of the week: Use the format() method again to format the resulting DateTime object as a string in the desired format (e.g., ‘Y-m-d’).