如何确定当前日期/时间是否在计划内?

时间:2015-04-12 11:55:40

标签: php

考虑到时间表:

{
  "start_day": "Monday",
  "end_day": "Friday",
  "start_time": "9:00 AM",
  "end_time": "6:00 PM"
}

如何确定指定时区内的当前时间是否属于上述给定的时间表? PHP中是否有任何功能可以帮助我?我预见的问题:

  1. 处理时区
  2. 给定的时间表不提供年份信息,但我想我可以假设它适用于当前年度
  3. 处理天数(星期一和星期五);我怎么知道星期二,星期三和星期四介于两者之间?
  4. 更新1:

    更改JSON,使其包含所有日期/时间:

    {
      "start_day": "Monday",
      "end_day": "Sunday",
      "start_time": "12:00 AM",
      "end_time": "11:59 PM"
    }
    

    然后将$now作业更改为$now = new DateTime("Saturday next month 10 am", $timezone);

    没有输出任何东西。

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码。我检查了该示例中所有可用的时区:

<?php

$json = <<<EOF
{
  "start_day": "Friday",
  "end_day": "Sunday",
  "start_time": "9:00 AM",
  "end_time": "6:00 PM"
}
EOF;

$when = json_decode($json);

// Get weekdays between start_day and end_day.
$start_day = new DateTime($start);
$nstart_day = (int) $start_day->format('N');
$end_day = new DateTime($end);
$nend_day = (int) $end_day->format('N');

// If the numeric end day has a lower value than the start
// day, we add "1 week" to the end day
if($nend_day < $nstart_day) {
    $end_day->modify('+1 week');
}
// Add one day to end_day to include it into the return array
$end_day->modify('+1 day');

// Create a DatePeriod to iterate from start to end
$interval = new DateInterval('P1D');
$period = new DatePeriod($start_day, $interval, $end_day);
$days_in_between = array();
foreach($period as $day) {
    $days_in_between []= $day->format('l');
}


// Check for all timezones in this example
foreach(DateTimeZone::listIdentifiers() as $tzid) {
    $timezone = new DateTimeZone($tzid);
    // Current time in that timezone
    $now = new DateTime("now", $timezone);
    // start_time in that timezone
    $start_time = new DateTime($when->start_time, $timezone);
    // end_time in that timezone
    $end_time = new DateTime($when->end_time, $timezone);
    // Get weekday for that timezone
    $day = $now->format('l');

    if($now >= $start_time && $now <= $end_time
        && in_array($day, $days_in_between))
    {
        printf("In %s the current time %s is between %s and %s (%s-%s)\n",
            $tzid, $now->format('H:i:s'), $when->start_time, $when->end_time,
                $when->start_day, $when->end_day);
    }
}