从两个时间戳中获取分钟数,在PHP中这两个时间戳是星期天

fquxozlt  于 2023-02-07  发布在  PHP
关注(0)|答案(2)|浏览(96)

我有两个时间戳,可以是任何日期和时间。我想获取星期天的所有分钟。为了更好地理解:开始时间戳和结束时间戳表示员工开始工作和完成工作的日期和时间,我想得到员工在星期天工作的总分钟数。
下面是我的代码:

function get_sunday_hours_from_timestamps($startTimestamp, $endTimestamp) {
    $start = new DateTime();
    $start->setTimestamp($startTimestamp);
    $end = new DateTime();
    $end->setTimestamp($endTimestamp);
    $workedMinutes = 0;
    $current = clone $start;
    while ($current <= $end) {
        $next = clone $current;
        $next->modify('next day');
        if ($current->format('w') == 0) {
            $dayStart = ($current < $start) ? $start : $current;
            $dayEnd = ($next > $end) ? $end : $next;
            $diff = $dayEnd->diff($dayStart);
            $minutes = $diff->days * 1440 + $diff->h * 60 + $diff->i;
            $workedMinutes += $minutes;
        }
        $current = $next;
    }

    return $workedMinutes / 60;
    // return $workedMinutes;
}
wwodge7n

wwodge7n1#

谢谢你的投入。我能够解决这个问题。希望这对其他人有帮助。

function get_sunday_hours_from_timestamps($startTimestamp, $endTimestamp) {
    $totalMinutes = 0;

    $startDay = strtotime("midnight", $startTimestamp);
    $endDay = strtotime("tomorrow", $endTimestamp) - 1;

    for ($currentDay = $startDay; $currentDay <= $endDay; $currentDay = strtotime("+1 day", $currentDay)) {
        if (date("l", $currentDay) == "Sunday") {

        $start = max($startTimestamp, $currentDay);
        $end = min($endTimestamp, strtotime("tomorrow", $currentDay) - 1);

        $totalMinutes += ($end - $start) / 60;
        }
    }

    return round($totalMinutes / 15) * 0.25;
}
bmvo0sr5

bmvo0sr52#

    • 警告**:下面的解决方案效率极低,速度极慢,特别是对于长时间段的输入。它只是以一种易于阅读的形式说明了一种幼稚的方法。您可以将其作为起点,但要明智地使用它!

一个非常简单的解决问题的方法(计算给定时间段内的星期天分钟数)可能是:反复检查你时间段内的每一分钟,检查一下那一分钟是否是星期天,然后计算一下。
在PHP中,可能类似于:

function isSunday(DateTimeInterface $dateTime) {
    return $dateTime->format('w') == 0;
}

function countSundayMinutes(DateTime $start, DateTime $end): int
{
    if ($start >= $end) {
        throw new LogicException('end must be > start!');
    }
    $sundayMinutes = 0;
    $current = clone $start;
    while ($current < $end) {
        if (isSunday($current)) {
            $sundayMinutes++;
        }
        $current = $current->add(DateInterval::createFromDateString('1 minute'));
    }

    return $sundayMinutes;
}

echo countSundayMinutes(new DateTime('2023-01-02 00:00'), new DateTime('2023-01-03 00:00')), PHP_EOL; // 0: total 24h, not on sunday
echo countSundayMinutes(new DateTime('2023-01-01 12:00'), new DateTime('2023-01-01 13:00')), PHP_EOL; // 60: total 60 minutes, thereof 60 on sunday
echo countSundayMinutes(new DateTime('2022-12-31 23:00'), new DateTime('2023-01-01 01:00')), PHP_EOL; // 60: total 12 minutes, thereof 60 on sunday
echo countSundayMinutes(new DateTime('2022-12-31 00:00'), new DateTime('2023-01-03 00:00')), PHP_EOL; // 1440: total 72h, thereof 24h (1440 minutes) on sunday

但是我相信你可以对这个算法进行很多优化,比如你可以先检查一下给定的时间段是否包括星期天...

相关问题