Alex
Alex

Reputation: 68104

php - match day of week in date() / time()

I'm trying to reschedule recurring events based on the recurring method: daily, weekly or monthly.

So assuming I have this data:

  $now = time();
  $start_date = '01/01/2011 14:00';
  $end_date = '01/01/2011 14:20';
  $start_time = date('H:i', $start_date);
  $end_time = date('H:i', $end_date);
  $period = $end_date - $start_date; // in this case, 20 minutes

This event rescheduled daily would be:

  $new_time_start = strtotime(date("m/d/Y {$start_time}", $now));
  $new_time_end = $new_time_start + $period;

And monthly:

  $start_day = date('d', $start_date);
  $new_time_start = strtotime(date("m/{$start_day}/Y {$start_time}", $now));
  $new_time_end = $new_time_start + $period;

It seems to be working, but I don't know how to do the same for weekly events :(

For example '01/01/2011' is Saturday, so I want to reschedule the event to run every Saturday (day 6 of the week according to PHP).

Any ideas?

Upvotes: 1

Views: 1169

Answers (2)

Benjam
Benjam

Reputation: 5316

Give this a try...

$today = date('w');
$day = date('w', $start_date);
$diff = abs(7 - ($today - $day));
$new_time_start = strtotime('+'.$diff.'days', strtotime(date("m/d/Y {$start_time}")));
$new_time_end = $new_time_start + ($end_date - $start_date);

It seems as though you're missing some strtotime( ) wrappers around your $start_date and $end_date values. I'm assuming your storing your start and end date variables as unix timestamps, so I didn't include them in my code either.

Also, just as a side note, you don't have to enter time( ) in date( ) as the second argument. If the time value is missing, it will use the current time. So you can remove all your $now instances and it will still work.

Upvotes: 1

JohnP
JohnP

Reputation: 50019

I'm not too sure I understand your question, but can't you do this?

$time       = '2011-01-31';
$weekLater  = date('Y-m-d', strtotime('+7 days ' . $time));
echo $time . ' -> ' . $weekLater;  

Output : 2011-01-31 -> 2011-02-07

Whatever date you give it, it will give you a date 7 days in the future. Is this what you need?

Upvotes: 1

Related Questions