我的应用程序需要在本地时间下午 6:00 向所有用户发送电子邮件。 服务器配置为 GMT。 我有一个在每小时开始时调用的函数。 我如何找出现在下午 6:00 的时区(PHP 时区)? (这样我就可以查询数据库并找到所有设置为该时区的用户并向他们发送电子邮件)。 也可以在不遍历整个时区数组的情况下做到这一点吗? 谢谢。
最佳答案
我之前的回答不太好,因为夏令时不允许您定义与格林威治标准时间的绝对偏移量的时区。这是一个更好的解决方案,假设您将时区存储在 one of these formats 中.该脚本应在每刻钟每 15 分钟运行一次。
// 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
编辑:根据 Catcall 的建议改编脚本以使用刻钟。
关于php - 计算哪些时区在 PHP 上具有特定的当前本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7249344/