考虑到时间表:
{
"start_day": "Monday",
"end_day": "Friday",
"start_time": "9:00 AM",
"end_time": "6:00 PM"
}
如何确定指定时区内的当前时间是否属于上述给定的时间表? PHP中是否有任何功能可以帮助我?我预见的问题:
更新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);
没有输出任何东西。
答案 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);
}
}