如何在午夜时分内获得UTC偏移量?

时间:2016-03-15 23:31:32

标签: php date datetime utc

我想在任何特定时刻确定哪个UTC偏移在00:0000:59之间。

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

1 个答案:

答案 0 :(得分:0)

使用DateTimeDateTimeZone 1 ,您可以创建一个有用的功能:

/*
    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. php TimeZone有一些错误(在TimeDiff中报告,但我提醒你)当原始DateTime不是UTC格式时。因此,在生产中使用之前,请检查功能行为。
  2. 在UTC时间13:43经过测试。
  3. 你要求“UTC偏移”,但是这个定义并不准确:可以有多个具有相同小时的TimeZones:所以,该函数返回一个数组。
  4. 在“时区”部分,您可以点击每一行跳转到相应的 zeitverschiebung.net 页面。请注意,有时站点上的UTC偏移量与php UTC偏移量不同:在我检查的日期中,php UTC偏移量是正确的。
相关问题