最简单的方法找到GMT偏移,当地时间是在某些小时之间


Easiest way to find GMT offsets where local time is between certain hours?

如果现在是伦敦时间凌晨2点,我如何查找当地时间在早上7点到晚上7点之间的GMT偏移量(秒)?

我有一个数据库记录与GMT偏移列(-3600,- 14400,28000等)。我希望能够根据偏移量大致在当地白天时间内的偏移量进行选择。现在,这些偏移中有哪些是在白天?我完全不知道该怎么处理这件事。

这比看起来更容易。如果您有从UTC午夜开始经过的时间,以秒为单位,如这里

$gmtSecondsSinceMidnight = (gmmktime() - gmmktime(0,0,0));

则时区应该在60*60*760*60*19秒距离内,相对于GMT。19是24小时制的7点。

$remoteTZStartZ1 = 7*$hour - $gmtSecondsSinceMidnight;
$remoteTZEndZ1 = 19*$hour - $gmtSecondsSinceMidnight;

这足以形成像

这样的查询
echo "SELECT name FROM timezones WHERE 
    (offsetSeconds > $remoteTZStartZ1 AND offsetSeconds < $remoteTZEndZ1);";

但是,如果remoteTZ变量超过12h偏移量,则需要构造两个额外的括号。否则,您可能会尝试选择偏移量大于12小时或小于-12小时的时区。将偏移量复制到±24h:

$remoteTZStartZ2 = $remoteTZStartZ1 - 24*$hour;
$remoteTZEndZ2 = $remoteTZEndZ1 - 24*$hour;
$remoteTZStartZ3 = $remoteTZStartZ1 + 24*$hour;
$remoteTZEndZ3 = $remoteTZEndZ1 + 24*$hour;

并使用如下的查询

echo "SELECT name FROM timezones WHERE 
    (offsetSeconds > $remoteTZStartZ1 AND offsetSeconds < $remoteTZEndZ1) OR 
    (offsetSeconds > $remoteTZStartZ2 AND offsetSeconds < $remoteTZEndZ2) OR 
    (offsetSeconds > $remoteTZStartZ3 AND offsetSeconds < $remoteTZEndZ3);";

likeitlikeit的回答帮助改进了我的工作,唯一缺少的是锚定在实际的时间戳中。我用这种方法粗略地解决了这个问题,尽管这可以大大改进:

date_default_timezone_set('Europe/London');
$currentTimestamp = time();
$startHour = strtotime("7am");
$endHour = $startHour+50400; //9pm
$start = ($startHour>$currentTimestamp) ? ($startHour - $currentTimestamp) : -1 * abs($currentTimestamp - $startHour);
$end = ($endHour>$currentTimestamp) ? ($endHour - $currentTimestamp) : -1 * abs($currentTimestamp - $endHour);

PHP在5.2版中有这个函数+ DateTimeZone::getOffset