How to add N weeks to the current date in PHP

1 Answer

0 votes
/**
 * Adds a specified number of weeks to the current system date.
 *
 * @param int $weeks The number of weeks to add (supports negative numbers to subtract).
 * @return DateTimeImmutable The resulting date as an immutable object.
 */
function addWeeksToCurrentDate(int $weeks): DateTimeImmutable 
{
    // 1. Get the current date and time as an immutable object
    $currentDate = new DateTimeImmutable();
    
    // 2. Use the modify() method with a relative string format (e.g., "+4 weeks")
    // This handles month transitions, leap years, and rollovers automatically.
    return $currentDate->modify("+{$weeks} weeks");
}

// ==========================================
// Example Usage:
// ==========================================

$weeksToAdd = 4;
$futureDate = addWeeksToCurrentDate($weeksToAdd);

// Output formatted as YYYY-MM-DD
echo "Today: " . (new DateTimeImmutable())->format('Y-m-d') . "\n";
echo "After adding {$weeksToAdd} weeks: " . $futureDate->format('Y-m-d') . "\n";



/*
run:

Today: 2026-11-07
After adding 4 weeks: 2026-12-05

*/

 



answered 1 day ago by avibootz
...