【问题标题】:How would I get the UTC offset currently within the midnight hour?我如何在午夜时分获得当前的 UTC 偏移量?
【发布时间】:2016-03-15 23:31:31
【问题描述】:

我想随时确定在00:0000:59 之间的UTC 偏移量。

有没有一种简洁的方法来获得这个而无需手动迭代偏移量?也许通过从 UTC 当前时间的转换?

【问题讨论】:

  • 这里是怎么回事?我有一个问题要解决并且我没有现有的算法。看起来很合身。
  • 关键是你必须试一试,否则我们不知道你遇到了什么问题。如果有人在这里实现了某些东西,那只是解决了您的问题。如果你展示你尝试过的东西,这个问题更有可能对其他人有用。

标签: php date datetime utc


【解决方案1】:

使用DateTimeDateTimeZone1 你可以创建一个有用的函数:

/*
    Return UTC Offsets/Timezones in which is 00AM at passed time string

    @param    string    original time string (default: current time)
    @param    string    original timezone string (default: UTC)
    @param    bool      return as Timezones instead as UTC Offests (default: False)

    @retval   array     array of UTC Offsets or Timezones
*/
function getMidNight( $timeString=Null, $timeZone=Null, $returnTimeZone=False )
{
    $utc = new DateTimeZone( 'UTC' );
    $baseTimeZone = ( $timeZone ) ? new DateTimeZone( $timeZone ) : $utc;
    $date = new DateTime( $timeString, $baseTimeZone );

    $retval = array();
    foreach( DateTimeZone::listIdentifiers() as $tz )
    {
        $currentTimeZone = new DateTimeZone( $tz );
        if( ! $date->setTimezone( $currentTimeZone )->format('G') )
        {
            if( $returnTimeZone ) $retval[] = $tz;
            else                  $retval[] = $date->getOffset();
        }
    }
    return array_unique( $retval );
}

G 格式是不带前导零的 24 小时,因此 00False->listIdentifiers() 返回所有已定义时区标识符的列表。

那么,这样调用2

print_r( getMidNight() );

您将获得3

Array
(
    [0] => 46800
    [1] => -39600
)

而且,以这种方式调用它2

print_r( getMidNight( Null, Null, True ) );

您将获得:

Array
(
    [0] => Antarctica/McMurdo
    [1] => Pacific/Auckland
    [2] => Pacific/Enderbury
    [3] => Pacific/Fakaofo
    [4] => Pacific/Midway
    [5] => Pacific/Niue
    [6] => Pacific/Pago_Pago
    [7] => Pacific/Tongatapu
)

phpFiddle demo 4


注意事项:

  1. 当原始 DateTime 不是 UTC 格式时,php TimeZone 有一些错误(在 TimeDiff 中报告,但我提醒你)。因此,在将其用于生产之前,请检查函数行为。
  2. 在 13:43 UTC/GMT 测试。
  3. 您要求提供“UTC 偏移量”,但此定义并不精确:同一小时可以有多个 TimeZone:因此,该函数返回一个数组。
  4. 在“TimeZones”部分,您可以点击每一行跳转到对应的 zeitverschiebung.net 页面。请注意,有时网站上的 UTC 偏移量与 php UTC 偏移量不同:在我检查过的日期中,php UTC 偏移量是正确的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 2010-09-27
    • 2013-08-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-17
    相关资源
    最近更新 更多