Calculate which time intervals have a specific current local time in PHP

My application should send an email to all users at 18:00 local time. The server is configured for GMT. I have a function that is called at the beginning of every hour. How to find out what time intervals (PHP timezones) are now at 18:00? (this way I can query the database and find all the users installed in this time zone and send them by email). Is it also possible to do this without repeating the entire timezone array? Thanks.

+4
source share
1 answer

My previous answer was not too large, because daylight saving time does not allow you to determine time intervals in absolute GMT offsets. Here's the best solution, assuming you store timestamps in one of these formats . This script should run every 15 minutes for a quarter of an hour.

// Target local time in hours (6:00 PM = 18:00) $targetHour = 18; // Get timestamp of nearest quarter-hour. // (Assuming this is being run by cron on-the-quarter-hour by server time) date_default_timezone_set('GMT'); $currentHourTimestamp = (round(time() / 900) * 900); // Calculate offset in hours to target hour $targetDateTime = new dateTime('@' . $currentHourTimestamp, new DateTimeZone('GMT')); $targetDateTime->setTime($targetHour, 0, 0); $targetOffset = $targetDateTime->getTimestamp() - $currentHourTimestamp; // You can get this from the database with a // 'SELECT DISTINCT timezones FROM users' query or similar $timezonesUsed = array('America/Los_Angeles', 'America/Phoenix', 'Europe/Budapest', 'Europe/Dublin'); $matchingTimezones = array(); foreach($timezonesUsed as $localTimezone) { // throws an Exception if timezone is not recognized $localDateTimezone = new DateTimeZone($localTimezone); $localOffset = $localDateTimezone->getOffset($targetDateTime); if($localOffset == $targetOffset) $matchingTimezones[] = $localTimezone; } // Now send emails to users in database with timezones in $matchingTimezones 

Edit: Adapted script to use a quarter hour on a Catcall offer.

+1
source

All Articles