Forked from glueckpress/calculate-utc-offset-dst.php
Created
January 30, 2019 20:51
-
-
Save inpresif/6f1a8e9a41cf56f5623980f2072a0150 to your computer and use it in GitHub Desktop.
Calculate a timezone’s offset to UTC considering daylight savings time (e.g. CEST), print a string like “UTC+2” or “UTC-9”
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Prints a string showing current time zone offset to UTC, considering daylight savings time. | |
* @link http://php.net/manual/en/timezones.php | |
* @param string $time_zone Time zone name | |
* @return string Offset in hours, prepended by +/- | |
*/ | |
function ch150918__utc_offset_dst( $time_zone = 'Europe/Berlin' ) { | |
// Set UTC as default time zone. | |
date_default_timezone_set( 'UTC' ); | |
$utc = new DateTime(); | |
// Calculate offset. | |
$current = timezone_open( $time_zone ); | |
$offset_s = timezone_offset_get( $current, $utc ); // seconds | |
$offset_h = $offset_s / ( 60 * 60 ); // hours | |
// Prepend “+” when positive | |
$offset_h = (string) $offset_h; | |
if ( strpos( $offset_h, '-' ) === FALSE ) { | |
$offset_h = '+' . $offset_h; // prepend + | |
} | |
return 'UTC' . $offset_h; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Will print “Berlin currently is UTC+2” during DST, | |
* otherwise will print “Berlin currently is UTC+1”. | |
* | |
* Which is the truth, and nothing but the truth. | |
*/ | |
$utc_offset = ch150918__utc_offset_dst(); | |
printf( 'Berlin currently is %s', $utc_offset ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment