如何知道当前时间是否在夏令时?

时间:2011-01-29 08:14:13

标签: php

我如何知道世界上某个特定城市的当前时间是否在夏令时?有PHP功能吗?

2 个答案:

答案 0 :(得分:4)

我不是一个PHP人,但看起来这是可行的 - 但很尴尬。

给定DateTimeZone,您可以找到当前偏移和一组转换。因此,如果您要求“现在”转换,您可以找到有关时区当前部分的信息。来自the docs的略微修改的示例:

$theTime = time(); # specific date/time we're checking, in epoch seconds. 

$tz = new DateTimeZone('America/Los_Angeles'); 
$transition = $tz->getTransitions($theTime,$theTime); 

# only one array should be returned into $transition.
$dst = $transition[0]['isdst']; 

答案 1 :(得分:2)

嗯,听起来isdst应该做正确的事情,但我之前一直被咬过,所以这里是PHP的C ++时区代码的快速端口:

// given a timezone and a timestamp
// return true if timezone has DST at timestamp, false otherwise
// timezone defaults to current timezone
// timestamp defaults to now
function is_dst($timezone = null, $time = null) {
    $oldtimezone = date_default_timezone_get();
    if (isset($timezone)) {
        date_default_timezone_set($timezone);
    }

    if (!isset($time)) {
        $time = time();
    }

    $tm = localtime($time, true);
    $isdst = $tm['tm_isdst'];
    $offset = 0;
    //$dsttime = mktime_array($tm);
    //echo strftime("%c", $dsttime);

    $tm['tm_isdst'] = 0;
    $nondsttime = mktime_array($tm);
    $offset = $nondsttime - $time;

    date_default_timezone_set($oldtimezone);

    return $offset != 0;
}

function mktime_array($tm) {
    return mktime($tm['tm_hour'], $tm['tm_min'], $tm['tm_sec'], $tm['tm_mon']+1, $tm['tm_mday'], $tm['tm_year']+1900, isset($tm['tm_isdst'])? $tm['tm_isdst']: -1);
}

您可以使用一些代码来测试它:

foreach (array(null, "Australia/Sydney", "UTC", "America/Los_Angeles") as $tz) {
    $isdst = is_dst($tz);
    if (isset($tz)) {
        echo $tz;
    }
    else {
        echo "current timezone";
    }
    echo " ";
    if ($isdst) {
        echo "has daylight savings now\n";
    }
    else {
        echo "has standard time now\n";
    }
}

// tests based on known transitions for Sydney (AEST)
foreach (array(null, "2011-04-03 01:59:00", "2011-04-03 02:00:00", "2011-10-02 01:59:00", "2011-10-02 03:00:00") as $timestr) {
    $tz = "Australia/Sydney";
    if (isset($timestr)) {
        $tm = strptime($timestr, "%Y-%m-%d %H:%M:%S");
        $time = mktime_array($tm);
    }
    else {
        $time = time();
    }
    $isdst = is_dst($tz, $time);
    if (isset($tz)) {
        echo $tz;
    }
    else {
        echo "current timezone";
    }
    echo " ";
    if ($isdst) {
        echo "has daylight savings at $timestr\n";
    }
    else {
        echo "has standard time at $timestr\n";
    }
}

对我来说,它会打印出来:

current timezone has daylight savings now
Australia/Sydney has daylight savings now
UTC has standard time now
America/Los_Angeles has standard time now
Australia/Sydney has daylight savings at 
Australia/Sydney has daylight savings at 2011-04-03 01:59:00
Australia/Sydney has standard time at 2011-04-03 02:00:00
Australia/Sydney has standard time at 2011-10-02 01:59:00
Australia/Sydney has daylight savings at 2011-10-02 03:00:00