首页 > 解决方案 > 返回两个日期php之间的星期日分钟

问题描述

我想计算两个给定日期之间的所有周日分钟。

 function getWeekEnd($startDate, $endDate)
  {
    $working_hours = [
        [0, 86400], // Sun
        null,
        null,
        null,
        null,
        null,
        null //Sat
    ];
    $start = new \DateTime($startDate);
    $end = new \DateTime($endDate);
    $seconds = 0; // Total working seconds
    // Calculate the Start Date (Midnight) and Time (Seconds into day) as Integers.
    $start_date = clone $start;
    $start_date = $start_date->setTime(0, 0, 0)->getTimestamp();
    $start_time = $start->getTimestamp() - $start_date;
    // Calculate the Finish Date (Midnight) and Time (Seconds into day) as Integers.
    $end_date = clone $end;
    $end_date = $end_date->setTime(0, 0, 0)->getTimestamp();
    $end_time = $end->getTimestamp() - $end_date;
    // For each Day
    for ($today = $start_date; $today <= $end_date; $today += 86400) {
        // Get the current Weekday.
        $today_weekday = date('w', $today);
        // Skip to next day if no hours set for weekday.
        if (!isset($working_hours[$today_weekday][0]) || !isset($working_hours[$today_weekday][1])) continue;
        // Set the office hours start/finish.
        $today_start = $working_hours[$today_weekday][0];
        $today_end = $working_hours[$today_weekday][1];
        // Adjust Start/Finish times on Start/Finish Day.
        if ($today === $start_date) $today_start = min($today_end, max($today_start, $start_time));
        if ($today === $end_date) $today_end = max($today_start, min($today_end, $end_time));
        // Add to total seconds.
        $seconds += $today_end - $today_start;
    }
    $time = date('H:i', $seconds);
    $hms = explode(":", $time);
    return ($hms[0] + ($hms[1]/60));
  }

目前我有这个但是如果我把 2019-11-22 22:00:00 变成 2019-11-28 10:00:00 我没有回报你有另一个功能还是修复这个功能?

非常感谢

标签: php

解决方案


也许尝试这样的事情:

<?php

function getSundayMinutes($dateFromString, $dateToString)
{
    $dateFrom = new \DateTime($dateFromString);
    $dateTo = new \DateTime($dateToString);
    $minutes = [
    "total" => 0
    ];

    if ($dateFrom > $dateTo) {
        return $minutes;
    }

    if (1 != $dateFrom->format('N')) {
        $dateFrom->modify('next sunday');
    }

    while ($dateFrom <= $dateTo) {
        $minutes[$dateFrom->format('Y-m-d')] = 1440;
        $minutes["total"] += 1440; 
        $dateFrom->modify('+1 week');
    }

    return $minutes;
}

$dateFromString = '2019-11-01';
$dateToString = '2019-11-19';
print_r(getSundayMinutes($dateFromString, $dateToString));

?>

由于 11 月有 3 个星期日,上面的代码将打印出来:

Array ( [total] => 4320 [2019-11-03] => 1440 [2019-11-10] => 1440 [2019-11-17] => 1440 )

我使用此处的代码php 函数获取日期范围内的所有星期一

BR


推荐阅读