Search code examples
phpdatedatetime

Get date for Monday and Friday for the current week


How can I get the date for Monday and Friday for the current week?

I have the following code, but it fails if current day is Sunday or Saturday.

$current_day = date("N");
$days_to_friday = 5 - $current_day;
$days_from_monday = $current_day - 1;
$monday = date("Y-m-d", strtotime("- {$days_from_monday} Days"));
$friday = date("Y-m-d", strtotime("+ {$days_to_friday} Days"));

Solution

  • Assuming your week starts on Monday you can use DateTime class with specific relative formats.

    To get the Monday and Friday for the current week:

    $mondayThisWeek = new DateTimeImmutable("monday this week");
    $fridayThisWeek = new DateTimeImmutable("friday this week");
    
    // so when current date is Sun, 07 Jan 2024
    // $mondayThisWeek will be Mon, 01 Jan 2024
    // $fridayThisWeek will be Fri, 05 Jan 2024
    

    To get Monday and Friday relative to a specific date:

    $referenceDate = new DateTimeImmutable("2024-01-07");
    $thatMonday = $referenceDate->modify("monday this week");
    $thatFriday = $referenceDate->modify("friday this week");
    
    // $thatMonday will be Mon, 01 Jan 2024
    // $thatFriday will be Fri, 05 Jan 2024
    

    If your week starts on (for example) Sunday then you will have to calculate Monday and Friday manually. Here is an example:

    $referenceDate = new DateTimeImmutable("2024-01-07");
    $dayOfWeek = (int) $referenceDate->format("w");
    // 0 = Sun
    // 1 = Mon
    // 2 = Tue
    // 3 = Wed
    // 4 = Thu
    // 5 = Fri
    // 6 = Sat
    
    if ($dayOfWeek === 0) {
        $mondayModifier = "next monday";
    } elseif ($dayOfWeek === 1) {
        $mondayModifier = "today";
    } else {
        $mondayModifier = "previous monday";
    }
    
    if ($dayOfWeek < 5) {
        $fridayModifier = "next friday";
    } elseif ($dayOfWeek === 5) {
        $fridayModifier = "today";
    } else {
        $fridayModifier = "previous friday";
    }
    
    $thatMonday = $referenceDate->modify($mondayModifier);
    $thatFriday = $referenceDate->modify($fridayModifier);
    
    // $thatMonday will be Mon, 08 Jan 2024
    // $thatFriday will be Fri, 12 Jan 2024