2012-03-07 168 views
2

我已浏览过关于SO的其他解决方案,它们都没有涉及以下方面的时区/ dst问题。时区和夏令时问题

我打电话给NOAA Tide Prediction APINOAA National Weather Service API,需要传递时间范围才能检索数据。对于我的数据库中的每个位置,我都将UTC的时区作为UTC偏移量,以及是否观察到夏令时(1或0)。我试图将某些日期(今天和明天)格式化为LST(本地标准时间)在它自己的时区中,因此我可以传递给这些API。

我很难弄清楚如何知道日期(如今天)是否在夏时制范围内。

这是我到目前为止有:

// Get name of timezone for tide station 
// NOTE: $locationdata->timezone is something like "-5" 
$tz_name = timezone_name_from_abbr("", $locationdata->timezone * 3600, false); 
$dtz = new DateTimeZone($tz_name);  

// Create time range 
$start_time = new DateTime('', $dtz); 
$end_time = new DateTime('', $dtz); 
$end_time = $end_time->modify('+1 day'); 

// Modify time to match local timezone 
$start_time->setTimezone($dtz); 
$end_time->setTimezone($dtz); 

// Adjust for daylight savings time 
if($locationdata->dst == '1') 
{ 
    // DST is observed in this area. 

    // ** HOW DO I KNOW IF TODAY IS CURRENTLY DST OR NOT? ** 

}   

// Make call to API using modified time range 
... 

我怎么能去这样做?谢谢。

回答

3

您可以使用PHP的时间和日期函数:

$tzObj = timezone_open($tz_name); 
$dateObj = date_create("07.03.2012 10:10:10", $tzObj); 

$dst_active = date_format($dateObj, "I"); 

如果DST是在指定日期活跃,$dst_active1,否则0

而是在调用date_create指定的时间,你也可以通过"now"接受当前日期和时间值。

但是,像乔恩提到的那样,同一时区内的不同国家可能会观察到DST,而其他国家则可能不会。

+0

然而,谨防这些问题。 https://bugs.php.net/bug.php?id=40743 https://bugs.php.net/bug.php?id=49914 https://bugs.php.net/bug.php? id = 51051 https://bugs.php.net/bug.php?id=51557 https://bugs.php.net/bug.php?id=52480 https://bugs.php.net/ bug.php ID = 54340 https://bugs.php.net/bug.php?id=54655 https://bugs.php.net/bug.php?id=55253 的https://错误。 php.net/bug.php?id=60873 https://bugs.php.net/bug.php?id=60960 https://bugs.php.net/bug.php?id=61022 https: //bugs.php.net/bug.php?id=61311 https://bugs.php.net/bug.php?id=61530 https://bugs.php.net/bug.php?id= 61955 – taiganaut 2012-05-17 00:42:09

+8

^我的上帝......... – 2013-04-29 11:33:34

1

对于我的数据库中的每个位置,我有时区作为UTC偏移以及是否观察到夏令时(1或0)。

这些信息不足。可以有多个时区都具有相同的标准偏移量,都观察DST,但在不同的时间执行DST转换。 (事实上​​,在历史上,他们也可以启动和停止观察夏令时数年。)

基本上,你的数据库应该包含时区ID,不偏移/ DST-真或假。 (假设PHP使用zoneinfo时区数据库,时区ID是一样的东西“欧洲/伦敦”。)

编辑:为了找到一个给定的DateTime的偏移量,你可以调用getOffset,然后你就可以用比较标准时间偏移量。但是除非你有明确的时区ID,否则冒着错误的区域冒险。

+0

函数'timezone_name_from_abbr(“”,$ locationdata-> timezone * 3600,false);'从偏移量中返回时区ID,所以'-5'可能会返回'America/New York'。 – 2012-03-07 18:13:23

+0

@cillosis:你是否依赖那个映射是准确的?因为它*会*不明确。将编辑回答具体的问题,虽然... – 2012-03-07 18:28:14

+0

我敢肯定,会有歧义,但目前我不关心这一点。我更关心的是确定一个地区目前是否正在观察DST。 – 2012-03-07 19:11:17

0

Cillosis, 我希望你没有使用Java!我一直在与时间战斗。我也与天气数据一起工作。我使用的大部分数据都在本地标准时间(忽略夏令时)。我还需要使用其他时区的时间,并发现Java一直在阅读我电脑的时区。我还不断遇到弃用的课程。我想出了一个可行的解决方案。这有点难听,所以我有很多文档记录,它只存在于一个函数中。我的解决方案是相对时间。我已将当地时间设置为UTC。我正在减去GMT偏移量而不是添加它。我并不在意实际的时间,我只关心两次之间的差异。它工作得很好。 祝你好运

+0

我使用PHP并最终实现了类似的解决方案。 – 2012-03-08 18:43:15