Adding X weeks to a date using PHP 5.2

Chuck Le Butt picture Chuck Le Butt · Mar 29, 2012 · Viewed 12.5k times · Source

My shared hosting package at 1and1 only includes PHP 5.2.17 -- so I can't use the DateTime object. Very annoying!

I currently have this code

$eventDate = new DateTime('2013-03-16'); // START DATE
$finishDate = $eventDate->add(new DateInterval('P'.$profile["Weeks"].'W'));

But obviously it won't work.

How can do I the same with code that will work with PHP5.2? (The code adds X number of weeks to a particular date.)

Answer

dan-lee picture dan-lee · Mar 29, 2012

Just get the timestamp with strtotime() and add x * seconds of a week

$newTime = strtotime('2013-03-16') + ($numberOfWeeks * 60 * 60 * 24 * 7); // 604800 seconds

or what I've just found out:

$newTime = strtotime('+'.$numberOfWeeks.' weeks', strtotime('2013-03-16'));

Alternatively you can utilize the DateTime class. Use the the method modify to change your date (like in strtotime):

$d = new DateTime('2013-03-16');
$d->modify('+'.$numberOfWeeks.' weeks');