Adding X weeks to a date using PHP 5.2
Asked Answered
I

2

5

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

Imposition answered 29/3, 2012 at 14:19 Comment(0)
E
12

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');
Enwomb answered 29/3, 2012 at 14:21 Comment(6)
strtotime() brings more problems than it seems to be. Use DateTime class function to avoid strange bugs when calculating periods and you will never miss even a second.Distract
@Paul You are aware that it's about the missing DateInterval in PHP 5.2? Of course there's always the other answer.Enwomb
And what about DateTime::modify(), which is from PHP 5.2.0 ? It also works with positive and negative values. Just few days ago I've corrected bug in my own product bec. I was calculating interval by difference of timestamps and on the margin of 2 (Oct-Nov) months was loosing 2 weeks. Corrected to DateTime implementation and that's it.Distract
@Paul I am aware of the whole set of DateTime, thanks. I just didn't came up with that at that specific time. My other answers always indicate to prefer the set of DateTime, DateInterval and DatePeriod. This one was a special case. And also when you have PHP 5.2 then strtotime is the least problem you've got!Enwomb
Ok, I will upvote after timeout, but I think it is better to improve this answer with one more solution.Distract
Hey, :) update your answer with DateTime and will upvote, I remember! There is 10 points left for you to have almost round rep :)Distract
O
4

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.

Overcareful answered 29/3, 2012 at 14:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.