我想比较时间,我不完全确定处理此问题的最佳方法。比较时间:上午7点,上午5点或上午10点什么时间接近?
我有次一个数组,它是联合国能够编辑。数组(“500”,“1100”,“1700”,“2300”);
500 =凌晨5:00等等
如果是6或早上7点,我可以运行什么样的逻辑来看看它是早上7点,什么时间是上午05点接近上午10点还是?
我不认为这是复杂的,但我只是想对我试图破解的东西一起找出一个体面的解决办法。
任何帮助或方向将不胜感激!
我想比较时间,我不完全确定处理此问题的最佳方法。比较时间:上午7点,上午5点或上午10点什么时间接近?
我有次一个数组,它是联合国能够编辑。数组(“500”,“1100”,“1700”,“2300”);
500 =凌晨5:00等等
如果是6或早上7点,我可以运行什么样的逻辑来看看它是早上7点,什么时间是上午05点接近上午10点还是?
我不认为这是复杂的,但我只是想对我试图破解的东西一起找出一个体面的解决办法。
任何帮助或方向将不胜感激!
让我们先从数组你有:
$values = array("500", "1100", "1700", "2300");
我们想要的是将其格式化为有效的时间字符串,很容易,我们只需在正确的位置插入“:”。对于我创建了一个功能:
function Format($str)
{
$length = strlen($str);
return substr($str, 0, $length - 2).':'.substr($str, $length - 2);
}
现在我们可以,我们可以转换为UNIX时间strtotime有效的字符串。现在的问题是找到更接近当前时间(我们得到time)
所以,我们可以遍历数组,转换它们,计算差异与当前时间(以绝对值),并选择一个导致较低的数字。下面是代码:
$now = time(); //current time
$best = false;
$bestDiff = 0;
for ($index = 0; $index < count($values); $index++)
{
$diff = abs($now - strtotime(Format($values[$index])));
if ($best === false || $diff < $bestDiff)
{
$best = $index;
$bestDiff = $diff;
}
}
它会留下的接近时间$best
指标,并与计算的$bestDiff
时刻的差异。请注意,这一切都是在同一天和当地时间。
的差的两倍
说07:00之间的绝对值 - 05:00 02:00 =,的02:00绝对值仍然02:00
07:00 - 10 :00 = -03:00,-03绝对值:00 03:00
在PHP中您可以使用您的strtotime时间字符串转换为秒:
$time_one = strtotime("07:00");
$time_two = strtotime("05:00");
$time_three = strtotime("09:00");
但你怎么做“0700” - “0500”? – 2012-10-12 06:30:53
无论何时使用strtotime() - http://php.net/manual/en/function.strtotime.php,您都会在自从时代以来以秒为单位返回的字符串中提到您的时间。这是一个可用于计算的数字 – vstrien
这里是我的解决方案:
// Input data
$values = array("500", "1100", "1700", "2300");
$time = "12:15";
// turns search time to timestamp
$search = strtotime($time);
// turns "500" to "5:00" and so on
$new = preg_replace('/^(\d?\d)(\d\d)$/','\1:\2', $values);
// converts the array to timestamp
$new = array_map('strtotime', $new);
// sorts the array (just in case)
asort($new);
// Some initialization
$distance = $closest = $result = $result_index = NULL;
// The search itself
foreach($new as $idx => $time_stamp)
{
$distance = abs($time_stamp - $search);
if(is_null($closest) OR $closest > $distance)
{
$closest = $distance;
$result_index = $idx;
$result = $time_stamp;
}
}
echo "The closest to $time is ".date('H:i', $result)." ({$values[$result_index]})";
我适应Theraot的解决方案,通过该值的距离排序的数组到当前时间:
<?php
$values = array("500", "1100", "1700", "2300");
$now = time();
/**
* Format an integer-string to a date-string
*/
function format($str)
{
$length = strlen($str);
return substr($str, 0, $length - 2).':'.substr($str, $length - 2);
}
/**
* Callback to compare the distance to now for two entries in $values
*/
$compare = function ($timeA, $timeB) use ($now) {
$diffA = abs($now - strtotime(format($timeA)));
$diffB = abs($now - strtotime(format($timeB)));
if ($diffA == $diffB) {
return 0;
}
return ($diffA < $diffB) ? -1 : 1;
};
usort($values, $compare);
print_r($values);
你期望的结果是在$值[0]现在。 请注意,此解决方案需要PHP版本> = 5.3
数学变得更有趣的价值'“0550”,“0615” - - 接近6:00?我建议首先归一化为小数单位 - 例如5:50是5.83 - 如果它只是需要看哪个更接近.. – 2012-10-12 06:14:49