【问题标题】:How can I determine that a given date is the day daylight savings takes effect?如何确定给定日期是夏令时生效的日期?
【发布时间】:2014-04-27 20:52:38
【问题描述】:
  • PHP 时区设置为 America/New_York
  • 服务器在 EDT 中
  • 所有访问服务器的客户端都在 EDT 中

今年,2014 年,时间在 3 月 9 日凌晨 2:00 提前一小时。

我知道我可以使用date('I'); 来确定我们是否在夏令时。我需要做的是确定今天是 DST 的第一天(春季还是秋季)

我正在寻找类似的东西:

function isFirstDayOfDST($date) {
    //Return true if today is FIRST day of DST 
}

echo isFirstDayOfDST('2013-03-09');
//true

echo isFirstDayOfDST('2013-03-10');
//false

这是我可以以编程方式执行的操作,还是我需要维护 DST 日期的内部日历?


更新

根据@MarcB 的评论DateTimeZone::getTransitions 看起来它得到了我需要的东西,特别是rubo77 页面上的示例。

function getTransitionsForYear($year=null, $tz = null){
    if(!$year) $year=date("Y");

    if (!$tz) $tz = date_default_timezone_get();
    $timeZone = new DateTimeZone($tz);

    if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
        $transitions = $timeZone->getTransitions(mktime(0, 0, 0, 2, 1, $year),mktime(0, 0, 0, 11, 31, $year));
        $index=1;
    } else {
        // since 1980 it is regular, the 29th element is 1980-04-06
            // change this in your timezone
            $first_regular_index=29;
            $first_regular_year=1980;
        $transitions = $timeZone->getTransitions();
        $index=($year-$first_regular_year)*2+$first_regular_index;
    }
    $temp   = array_slice($transitions, $index, 2);
    $spring = explode('T', $t[0]['time']);
    $fall   = explode('T', $t[1]['time']);

    $dates = array();
    $dates['spring'] = $spring[0];
    $dates['fall'] = $fall[0];

    return $dates;
};

运行$dates = getTransitionsForYear('2014', 'America/New_York'); 得到我:

Array
(
    [spring] => 2014-03-09
    [fall] => 2014-11-02
)

我已经对 2015、2016 和 2017 年进行了测试,一切都按预期工作。

【问题讨论】:

  • 你不能。夏令时是一个政策问题,所以没有算法可以用来解决这个问题。您必须按照您的建议进行操作并保留 DST 日期的数据表,然后执行查找。
  • 最好保留系统上的日期,然后检查当前日期是否与您列出的 DST 日期之一匹配。
  • @MarcB,愿意回答吗?我知道如何使用它来获得我需要的东西。

标签: php timezone


【解决方案1】:

@Marc B 的评论回答了这个问题。 “php.net/manual/en/datetimezone.gettransitions.php 应该会告诉你。——Marc B”

由于他没有给出答案,所以我自己回答并将其标记为 CW,如下所述:Question with no answers, but issue solved in the comments (or extended in chat)

【讨论】:

    猜你喜欢
    • 2013-05-25
    • 2013-11-16
    • 2010-09-07
    • 2010-09-09
    • 2020-04-29
    • 2015-09-17
    • 2013-11-20
    • 2010-10-19
    • 2012-12-21
    相关资源
    最近更新 更多