PHP DateTimeZone->getOffset()

Today I had to use PHP’s DateTimeZone->getOffset() to get a timezone offset. It needed formatting which I did with:

function timezone_offset() {
  $offset = timezone()->getOffset( now() );
  $hours = round( abs( $offset ) / 3600 );
  $minutes = round( ( abs( $offset ) - $hours * 3600 ) / 60 );
  $result = ( $offset < 0 ? '-' : '+' )
    . ( $hours < 10 ? '0' : '' ) . $hours
    . ':'
    . ( $minutes < 10 ? '0' : '' ) . $minutes; 
  return $result;
}

Leave a Reply