比较时间:现在是早上7点,什么时间接近凌晨5点或10点



我正在尝试比较时间,但我不完全确定处理此问题的最佳方法。

我有一系列无法编辑的时间。数组("500"、"1100"、"1700"、"2300");

500 = 5:00am 等...

如果是早上6点或7点,

我能运行什么样的逻辑来找出是早上7点,什么时间接近凌晨5点或10点?

我不认为这很复杂,但我只是想找出一个像样的解决方案,而不是我试图把一些东西放在一起。

任何帮助或指导将不胜感激!

让我们从您拥有的数组开始:

$values = array("500", "1100", "1700", "2300");
我们

想要的是将其格式化为有效的时间字符串,这很容易,我们只需在正确的位置插入":"即可。为此,我创建了一个函数:

function Format($str)
{
    $length = strlen($str);
    return substr($str, 0, $length - 2).':'.substr($str, $length - 2);
}

现在我们可以得到有效的字符串,我们可以用strtotime将其转换为unix时间。现在的问题是找到更接近当前时间(我们随着时间的推移得到的时间)

因此,我们可以迭代数组,转换它们,计算与当前时间(绝对值)的差值,然后选择导致较低数字的数组。这是代码:

$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。请注意,这一切都假设这些时间是同一天和当地时间。

我改编了 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);

你想要的结果现在在$values[0]中。注意,这个解决方案需要 php 版本>= 5.3<</p>

div class="one_answers">

两次之差的绝对值

假设 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");

这是我的解决方案:

// 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)(dd)$/','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]})";

最新更新