Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding X weeks to a date using PHP 5.2

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

like image 514
Chuck Le Butt Avatar asked Mar 29 '12 14:03

Chuck Le Butt


2 Answers

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');
like image 115
dan-lee Avatar answered Sep 25 '22 18:09

dan-lee


You can use the DateTime object in PHP 5.2, it's just the add method that was added in PHP 5.3. You can use the modify method in PHP 5.2.

$finishDate = $eventDate->modify('+'.$profile["Weeks"].' weeks');

Please note that this will modify the object on which you perform the operation. So $eventDate will be altered too.

like image 20
Bas Avatar answered Sep 26 '22 18:09

Bas