首页 > 解决方案 > PHP 广播日历

问题描述

在电视行业,他们使用广播日历,它与公历的不同之处在于将上个月的天数拉入以创建当前月份。每个月正好有 4 或 5 周,而这一周总是从星期一开始。

此处有关于此日历的更多信息: https ://en.wikipedia.org/wiki/Broadcast_calendar

更新了广播日历示例

我正在努力实现三件事:

1) 一个 PHP 函数,我可以在其中提供特定日期并让它返回广播月份

function getBroadcastMonth('2019-10-16'){
   //Return broadcast month
   return 10;
}

2) 一个 PHP 函数,我可以在其中提供特定日期并让它返回广播

function getBroadcastWeek('2019-10-16'){
   //Return broadcast week
   return 42;
}

3)我可以获得广播月的第一天和最后一天的功能。

function getFirstAndLast(10){
   //Return first and last day of the given broadcast month
   return array('first_day' => '2019-09-30', 'end' => '2019-10-27');
}

我试图构建一个函数来至少在一个数组中构建一个日历,所以我可以以某种方式使用它来获得我需要的结果,但是我并没有走得太远。这是那个代码。

$now = new DateTime();

$from = (new DateTime)->setISODate($now->format('Y') - 1, 1);
$from->modify("monday this week"); // see ISO 8601 

while($from < $now) {
    echo $from->format('W  --  d/M/Y').'<br />';
    $from->modify("+1 week");
}

有人能帮我解决这个问题吗?

这里还有一个示例说明如何在 SQL Server 中完成此操作。

标签: phpcalendar

解决方案


这里有一组功能可以满足您的需求。您可能想考虑将它们包装到一个类中……毫无疑问,可以进行一些优化。

function makeBroadcastCalendar($start_date, $end_date) {
    $end = new DateTime($end_date);
    $start = new DateTime($start_date);
    $start->modify('monday this week');
    $week = 1;
    $weeks = array();
    while($start < $end) {
        $weeks[$week++] = $start->format('Y-m-d');
        $start->modify('+1 week');
    }
    return $weeks;
}

function getBroadcastMonth($date) {
    $end_of_week = new DateTime($date);
    $end_of_week->modify('sunday this week');
    return (int)$end_of_week->format('n');
}

function getBroadcastWeek($date) {
    $start = new DateTime($date);
    $start->modify('January 1');
    $start->modify('monday this week');
    $start_of_week = new DateTime($date);
    $start_of_week->modify('monday this week');
    $week = 1;
    while ($start < $start_of_week) {
        $start->modify('+1 week');
        $week++;
    }
    return $week;
}

function getFirstAndLast($year, $month) {
    $start = new DateTime("$year-$month-01");
    $end = clone $start;
    $start->modify('monday this week');
    $output = array('first_day' => $start->format('Y-m-d'));
    $end->modify('+1 month');
    $end->modify('monday this week');
    while ($start < $end) {
        $start->modify('+1 week');
    }
    $output['end'] = $start->modify('-1 day')->format('Y-m-d');
    return $output;
}

您可以在 3v4l.org 上的演示中看到它们的运行情况


推荐阅读