/**
* Adds a specified number of weeks to a given date.
*
* @param DateTimeImmutable|string $date The starting date (string or DateTimeImmutable).
* @param int $weeks The number of weeks to add
* (supports negative numbers to subtract).
* @return DateTimeImmutable The resulting date as an immutable object.
* @throws Exception If the provided date string is invalid.
*/
function addWeeksToDate(DateTimeImmutable|string $date, int $weeks): DateTimeImmutable
{
// If the input is a string, convert it into a DateTimeImmutable object
$dateTime = is_string($date) ? new DateTimeImmutable($date) : $date;
// Construct an ISO 8601 duration interval string for weeks (e.g., "P2W" for 2 weeks)
$interval = new DateInterval("P{$weeks}W");
// Add the interval and return a new DateTimeImmutable instance
return $dateTime->add($interval);
}
// ==========================================
// Example Usage:
// ==========================================
try {
$startDate = '2026-06-01';
$weeksToAdd = 4;
$newDate = addWeeksToDate($startDate, $weeksToAdd);
// Output the formatted result
echo "Starting Date: " . $startDate . "\n";
echo "After adding {$weeksToAdd} weeks: " . $newDate->format('Y-m-d') . "\n";
// Output: 2026-06-29
} catch (Exception $e) {
echo "Error parsing date: " . $e->getMessage();
}
/*
run:
Starting Date: 2026-06-01
After adding 4 weeks: 2026-06-29
*/