Question

This is what I have:

Start Date (yyyy-mm-dd)  
Interval : n   
Interval Type : hour, day, week, month, year 

This is what I need: is the current time/date in the recurring interval

Data/Example:  
Today : 2013-07-16 12:37  

Event Data :  
Start Date : 2012-04-03 12:30  
Interval : 2  
Interval Type : week  

2012-04-03 is a Tuesday. So is 2013-07-16. How to calculate (in PHP) if the recurrence of every second tuesday will hit todays date or be last tuesday?

Any one?

Edit:
@hek2mgl I made it work this way

/* Check for recurring window is legit */
$interval_string ="P".$mm["mm_reoc_interval"];
switch ($mm["mm_reoc_interval_type"])
{
    case 1: $interval_string .= "H"; break;
    case 2: $interval_string .= "D"; break;
    case 3: $interval_string .= "W"; break;
    case 4: $interval_string .= "M"; break;
    case 5: $interval_string .= "Y"; break;
}

$start = DateTime::createFromFormat("Y-m-d H:i:s", $mm["mm_reoc_start_date"]." ".$mm["mm_reoc_start_hour"].":00");
$end = DateTime::createFromFormat("Y-m-d H:i:s", $date_time);
$interval = new DateInterval($interval_string);
$occurrences = 3;
$period = new DatePeriod($start,$interval,$end);
foreach($period as $dt){
  $date_array[] = $dt->format("Y-m-d");
}

if(in_array($today, $date_array)) 
{
       bla.bla..
    }
Was it helpful?

Solution 2

You can use the DateTime class together with relative datetime formats:

$dt = new DateTime('2012-04-03 12:30 +2 weeks');
$now = new DateTime();

if($dt->format('Y-m-d') === $now->format('Y-m-d')) {
    echo "it's today";
}

Check this manual to see which identifier can be used in relative date time formats.

OTHER TIPS

This should do the trick:

<?php
$start = "2012-04-03";
$compare = "2013-07-17";

$start_date = new Datetime($start); 
$compare_date = new Datetime($compare);
$diff = $start_date->diff($compare_date);
$diff_d = ($diff->days);

$round = (int)($diff_d/14); // 14: every 2nd week!
$diff_d2 = $round * 14;

if (0==$diff_d-$diff_d2) {
   echo "<br>Today is the day!";
} else {
   $d1 = $start_date->add(new DateInterval ("P" . $diff_d2 . "D"));
   echo "Last match was " . $d1->format('Y-m-d');
}
?>

you can use strtotime

you can say things like strtotime("+1 week"); strtotime("+1 month");

to work relative to a specific time other than current time, pass in the unix epoch time value to the second parameter of strtotime

Watch DatePeriod class (and DateInterval).

Specially this example can be useful, I hope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top