Given the schedule:
{
"start_day": "Monday",
"end_day": "Friday",
"start_time": "9:00 AM",
"end_time": "6:00 PM"
}
How can I determine if the current time in a specified time zone falls within the above given schedule? Are there any functions in PHP that'll help me? Issues that I foresee:
UPDATE 1:
Change JSON so it encompasses all days/times:
{
"start_day": "Monday",
"end_day": "Sunday",
"start_time": "12:00 AM",
"end_time": "11:59 PM"
}
Then change $now
assignment to $now = new DateTime("Saturday next month 10 am", $timezone);
Nothing is outputted.
You can use the following code. I check for all available timezones in that example:
<?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)
",
$tzid, $now->format('H:i:s'), $when->start_time, $when->end_time,
$when->start_day, $when->end_day);
}
}