Adding X weeks to a date using PHP 5.2
Question
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.)
Solution
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');
OTHER TIPS
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.