Reputation: 107
I am looking for two values in an array:
Here is the array:
$dates = array(
'08/29/2013 08:00',
'08/29/2013 08:10',
'08/29/2013 08:11',
'08/29/2013 12:20',
'08/29/2013 12:21',
'08/29/2013 12:21',
'08/29/2013 17:30',
); // etc.
Upvotes: 1
Views: 1674
Reputation: 11450
One of the best ways to compare times is to convert your strings to times using strtotime()
.
// Original array of date strings
$dates = array(
'08/29/2013 08:00',
'08/29/2013 08:10',
'08/29/2013 08:11',
'08/29/2013 12:20',
'08/29/2013 12:21',
'08/29/2013 12:21',
'08/29/2013 17:30',
);
// Make a new array of time stamps based on your strings
$dates_dt = array();
foreach($dates as $date)
$dates_dt[] = strtotime($date);
// Same idea with the dates you want to look at
$date_last1 = strtotime('08/29/2013 08:00');
$date_last2 = strtotime('08/29/2013 13:00');
$date_first1 = strtotime('08/29/2013 12:00');
$date_first2 = strtotime('08/29/2013 17:00');
Here's the magic - some pretty simple functions that return the closest date before (or the first entry), and the closest after (or the last) in your array.
function dateBefore($date, $dateArray){
$prev = $dateArray[0];
foreach( $dateArray as $d ){
if( $d >= $date )
return date("Y-m-d H:i", $prev);
$prev = $d;
}
}
function dateAfter($date, $dateArray){
foreach( $dateArray as $d ){
if( $d > $date )
return date("Y-m-d H:i", $d);
}
return date("Y-m-d H:i", end($dateArray));
}
echo dateBefore($date_last1, $dates_dt); // Outputs: 2013-08-29 08:00
echo dateBefore($date_last2, $dates_dt); // Outputs: 2013-08-29 12:21
echo dateAfter($date_first1, $dates_dt); // Outputs: 2013-08-29 12:20
echo dateAfter($date_first2, $dates_dt); // Outputs: 2013-08-29 17:30
Note Probably a good idea to sort the array of times as well so they're for sure in order.
foreach($dates as $date)
$dates_dt[] = strtotime($date);
// Add sort here
sort($dates_dt);
Upvotes: 1
Reputation: 3401
$nearest = $dates[0];
$now = time();
for ($i = 0; $i < count($dates); $i++) {
$date = $dates[$i];
$timestamp = strtotime($date);
if (abs(strtotime($date) - $now) < abs(strtotime($nearest) - $now))
$nearest = $date;
}
echo $nearest;
Upvotes: 0
Reputation: 428
You can convert all of the string timestamps to long values (milliseconds since 1970 epoch). Then just calculate the delta for relevant values (greater than 08/29/2013 08:00, for instance) compared to the upper limit (08/29/2013 13:00, for instance). The smallest delta is the closest to the upper limit. The greatest delta is furthest.
This is how you calculate the seconds since epoch: http://php.net/manual/en/function.strtotime.php
Upvotes: 0