php - 计算哪些时区在 PHP 上具有特定的当前本地时间

标签 php timezone

我的应用程序需要在本地时间下午 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/

相关文章:

php - 使用 php 将我的 sql 数据库上传到我的 html 表单中

php - Laravel 4.2 联盟

php - 在CURLOPT_HEADERFUNCTION设置的回调函数中终止HTTP请求是否可以?

python - 如何计算python中两个时区之间的时差?

php - Laravel 5 重定向函数源代码

php - 将 where 子句添加到 Doctrine 原生查询构建器

python - 为什么 Pytz 对纽约和底特律有不同的时区列表?

perl - 如何为 DateTime 提供缩写时区

java - 从人类可读的时区字符串中获取时区 ID

django - 带有用户时区的日期时间str