我如何在午夜时间获得当前的 UTC 偏移量?

问题描述 投票:0回答:1

我想在任何给定时刻确定哪个UTC偏移量在

00:00
00:59
之间。

有没有一种简洁的方法可以在不诉诸于手动迭代偏移量的情况下得到这个?也许通过 UTC 当前时间的转换?

php date datetime utc
1个回答
0
投票

使用

DateTime
DateTimeZone
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 小时,没有前导零,所以在
00
False
->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
)

备注:

  1. php TimeZone 在原始 DateTime 不是 UTC 格式时有一些错误(在 TimeDiff 中报告,但我提醒你)。所以,在生产中使用它之前检查功能行为。
  2. 在 13:43 UTC/GMT 测试。
  3. 您要求“UTC 偏移量”,但这个定义并不精确:同一小时可以有多个时区:因此,该函数返回一个数组。
© www.soinside.com 2019 - 2024. All rights reserved.