我在PHP数组中有一个日期/时间项的列表,其格式如下:
2019-03-19 00:00:00
2019-03-19 02:30:00
2019-03-19 05:00:00
2019-03-19 14:30:00
2019-03-19 23:59:59
etc.
我确信这很容易,我只是无法将头缠住它。我使用什么方程式来显示最接近当前时间的项目,而又不会越过。
因此,如果当前时间是22:00:00,我想显示项目14:30:00,而不是23:59:59。
答案 0 :(得分:2)
由于您的时间在Y-m-d H:i:s
中,因此您可以将它们作为字符串进行比较,并使用简单的foreach循环获取结果:
$dates = array('2019-03-19 00:00:00',
'2019-03-19 02:30:00',
'2019-03-19 05:00:00',
'2019-03-19 14:30:00',
'2019-03-19 23:59:59');
$now = date('Y-m-d H:i:s');
$latest = '';
// add sort($dates) here if they are not already sorted.
foreach ($dates as $date) {
if ($date > $now) break;
$latest = $date;
}
echo $latest;
请注意,此代码假定您的日期已经过排序,否则请在sort($dates)
循环之前添加foreach
。
答案 1 :(得分:0)
首先将所有日期转换为此格式
$changed_date_1 = date('YmdHis', strtotime($orignaldate_1));
$changed_date_2 = date('YmdHis', strtotime($orignaldate_2));
$changed_date_3 = date('YmdHis', strtotime($orignaldate)_3);
因此2019-03-19 00:00:00将变为20190319000000,依此类推,现在可以轻松进行比较了。 而不是运行一个遍历所有这些日期的foreach循环
$closestdate= date('Y-m-d H:i:s');//intaily set it to current date
$closest_difference= 99999999999999999;//intaily set a big value, more than 15 digits
foreach($datesArray as $item){
$difference = $item - date('YmdHis');
if($difference < $closest_difference){
$closes_difference = $difference;
$closestdate = $item;//this item is closest one. in next iteration this may change
}
}
echo $Closesdate;
答案 2 :(得分:0)
/**
* Gets the nearest moment of the same day as $today.
*
* @param string[] $dates - A list of dates (needed format: "Y-m-d H:i:s")
* @param string|null $today - The date used for comparaison. (default is current date)
* @return string|bool - Returns the nearest date, or false.
*/
function getNearestDate(array $dates, ?string $today = null) {
if (!$today) {
$today = date('Y-m-d H:i:s');
}
$fnDT = function($d) {
return DateTime::createFromFormat('Y-m-d H:i:s', $d);
};
usort($dates, function($a, $b) use ($fnDT, $today) {
$da = abs($fnDT($today)->getTimestamp() - $fnDT($a)->getTimestamp());
$db = abs($fnDT($today)->getTimestamp() - $fnDT($b)->getTimestamp());
return $da - $db;
});
$nearest = $dates[0];
if ($fnDT($nearest)->format('Y-m-d') !== $fnDT($today)->format('Y-m-d')) {
print_r('No date of the same day.');
return false;
}
return $nearest;
}