Pergunta

I am working on generating recurring dates using PHP to process the dates. I have a $startDateTime and $endDateTime. These two variables are for the first date in the series.

If the even repeats every Tuesday I need something along the lines of

 $repeatDay = "Tuesday";
 $followingDay = strtotime($startDateTime. " following $repeatDay");

Using "next $repeatDay" doesn't work since I am not generating the date from todays date.

EDIT:

It seems that every five loops the time jumps forward an hour in the date. This may be because $start="2014-04-29 11:00:00" and strtotime is only converting the date correctly.

How should I convert 2014-04-29 11:00:00 to a format that strtotime understands?

 $firstOccurrence=strtotime($start);
 $nextOccurence=strtotime("next $day", $firstOccurrence); //Set the first recurring date for this day
 while($nextOccurence<=strtotime($activeUntil)){
      echo date("M d, Y H:m:i",$nextOccurence)." | ";
      $nextOccurence=strtotime("next $day", $nextOccurence); 
 } 
Foi útil?

Solução

Maybe it's time to start working with DateTime? It's pretty complex in modyfing dates. For example, creating date time from your $start would look like this:

$start="2014-04-29 11:00:00";
$dateTime=DateTime::createFromFormat("Y-m-d H:m:i", $start);

And as you have $dateTime, you can modify it by one day:

$dateTime->modify('+1 day');
//or just
$dateTime->modify('next tuesday');
//and return it as string
echo $dateTime->format("M d, Y H:m:i");

DateTime understands everything that strtotime does, so it can improve your solution. Try it out yourself, and let me know if this helps.

Outras dicas

strtotime() can take 2 parameters. The first is the string and the second is the base timestamp.

Try the following:

// Assuming $startDateTime is a timestamp.
$followingDay = strtotime("next $repeatDay", $startDateTime);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top