Cesar Bielich
Cesar Bielich

Reputation: 4945

how to find the next closest date (month/day/time) without specifying year

I have a script that a user can setup a frequency as to when they want it to run.

They specify

They do not specify the year, the script needs to find the next closest date that matches.

PHP

The way I propigate the dates is through an array of months the user chooses and I can output all the dates into a nice array

$scheduler_months = unserialize($row['scheduler_months']);
foreach ($scheduler_months as $scheduler_month) {
    $next_date[] = $scheduler_month."/".$row['scheduler_date']." ".$row['scheduler_time'];
}

which will out put

Array ( [0] => 2/28 12:00 [1] => 4/28 12:00 [2] => 12/28 12:00 )

So now at this point I need to figure out what the next closest date based on today as the starting point will be, obviously if the next closest date is in the next year it needs to be smart enough to figure that out. I just have no idea how to find the next closest date based on the dates in the array.

Upvotes: 0

Views: 331

Answers (1)

man0v
man0v

Reputation: 674

It's quite easy to figure out the year of the dates - if you were to convert them to unix time using strtotime you can determine if this year's date was in the past or not and if it were, you can assign that date next year.

$scheduler_months = unserialize($row['scheduler_months']);
$now = strtotime("now"); # get the unix time in seconds 'now'
foreach ($scheduler_months as $scheduler_month) { 
    # $tmp will be holding the date in the form of YYYY-MM-DD HH:MM
    $tmp = date("Y")."-".$scheduler_month."-".$row['scheduler_date']." ".$row['scheduler_time'];
    if(strtotime($tmp) - $now < 0) # if date is in the past, assign it to the next year
            $tmp = (date("Y")+1)."-".$scheduler_month."-".$row['scheduler_date']." ".$row['scheduler_time'];
    $next_date[] = $tmp;
}

# Initialize $smallest and $smallest_key
$smallest = strtotime($next_date[0])-$now;
$smallest_key = 0;

foreach($next_date as $key => $val) {
        $time_diff = strtotime($val) - $now;
        if($time_diff < $smallest) {
                $smallest_key = $key;
                $smallest = $time_diff;
        }
}

In the first part, I've modified your foreach loop to determine the correct year based on unix time. I've changed the date format to YYYY-MM-DD HH:MM. If the date's unixtime is less than the current unix time, then the next closest date is next year.

In the second part I initilize two variables - $smallest, which holds the smallest time in seconds relative to now and $smallest_key, which holds the array key for the smallest time.

Then I loop over $next_date and I look for the smallest time in seconds from now to either of the dates.

Upvotes: 1

Related Questions