开发者

calculate which timezones have a specific current local time on PHP

开发者 https://www.devze.com 2023-03-31 16:27 出处:网络
My application needs to send an email to all users at 6:00PM, on their local time. The server is configured to GMT.

My application needs to send an email to all users at 6:00PM, on their local time. The server is configured to GMT. I have a function that is being called at the beginning of each hour. How do I find out which timezones (PHP timezones) a开发者_高级运维re now at 6:00PM? (this way I can query the data base and find all users set to this timezone and send them the email). Also is it possible to do it without iterating over the entire timezone array? Thanks.


My previous answer wasn't too great since daylight savings time precludes you from defining timezones in absolute offsets from GMT. Here's a better solution, assuming you're storing timezones in one of these formats. This script should be run every 15 minutes on the quarter-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 quarter-hours per Catcall's suggestion.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号