jz3
jz3

Reputation: 521

Incrementing PHP Dates

I am writing a part of an application where a user can add an event that spans multiple days. So I get in the post $begindate, $enddate, and $type. Type will be daily, weekly, or monthly. I'm trying to process the request for daily right now. What I need to do is do an insert into a my dates table a row for each day including the begindate, enddate, and each day in between if daily is selected. Since months have different amounts of days obviously, and I can't simply add 1 or 7 to the day part of the php date how would I approach this?

I do

$begindate = date('Y-m-D', strtotime($begindate))

for all dates when I receive the post.

I haven't worked too much with PHP date objects, any help would be appreciated.

Upvotes: 0

Views: 151

Answers (2)

Problematic
Problematic

Reputation: 17678

First, use the DateTime class if at all possible. Then, check out DateTime::add().

Also, the DatePeriod class can automatically create a series of DateTime objects at the interval that you request, which will make it a lot easier to accept different recurrence intervals:

$start = new \DateTime($beginDate);
$end = new \DateTime($endDate);
$interval = new \DateInterval('P1D');
$period = new \DatePeriod($start, $interval, $end);
foreach ($period as $day) {
    // will iterate over each day in the period
}

DateTime is really quite flexible in the strings it accepts in its constructor (check out the reference here), which makes it pretty trivial to get dates from today. For example, if you want a DateTime object that represents one week from right now, $date = new \DateTime('+1 week'); will do that for you.

Upvotes: 3

gintas
gintas

Reputation: 2178

$days = 1; // Or 7 or 30, or anything..
$nextday = date('Y-m-D', strtotime($begindate) + 86400 * $days);

Or use DateTime object.

$days = 1; // Or again 7.. or 30..

$begin = new DateTime($begindate);
$begin->add(new DateInterval('P' . $days . 'D'));
$nextday = $date->format('Y-m-D');

If you need to add extra weeks or months check DateInterval for details.

Upvotes: 2

Related Questions