【问题标题】:How to determine if current date/time is within a schedule?如何确定当前日期/时间是否在计划内?
【发布时间】:2015-04-12 11:55:40
【问题描述】:

鉴于时间表:

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

如何确定指定时区的当前时间是否在上述给定的时间表内? PHP 中有什么函数可以帮助我吗?我预见的问题:

  1. 处理时区
  2. 给定的时间表没有提供年份信息,但我想我可以假设它适用于当年
  3. 处理日期范围(提供周一和周五;我怎么知道中间有周二、周三和周四?

更新 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);

什么都没有输出。

【问题讨论】:

  • 看看DateTime objects,它处理时区
  • 1.这些时间是否也在指定的时区? 2. 所以说你只想要一个“简单”的 if 语句来告诉当前时间是否在计划之间,对吧? 3. 你有没有尝试过?
  • 计划没有指定时区。我一直在玩弄一些 PHP 函数来尝试让事情正常工作,主要是 strtotime

标签: php


【解决方案1】:

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

<?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);
    }
}

【讨论】:

  • 为什么要检查所有时区?以及如何检查周二上午 9 点至下午 6 点?
  • 这只是一个例子,这就是我检查所有时区的原因。当然,在您的应用程序中,您只需要检查目标时区。你没有给它命名。 And how does this check for Tuesday 9am-6pm?
  • 好的,我知道你是怎么过日子的,然后检查一下in_array。如果检查时间表的时间不是当前时间怎么办?说它是过去还是未来的某个时间?
  • 我猜你的next week 是任意的。可能是next monthlast week,对吧?我想如果检查的时间不是now,那么需要对添加的那些任意时间做点什么???
  • next week 技巧将有效,即使日期是过去或将来。它只是使用日期名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-19
  • 2012-04-05
  • 1970-01-01
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多