| 1 |
<?php |
| 2 |
|
| 3 |
namespace PhpOffice\PhpSpreadsheet\Shared; |
| 4 |
|
| 5 |
use DateTimeZone; |
| 6 |
use PhpOffice\PhpSpreadsheet\Exception as PhpSpreadsheetException; |
| 7 |
|
| 8 |
class TimeZone |
| 9 |
{ |
| 10 |
/** |
| 11 |
* Default Timezone used for date/time conversions. |
| 12 |
* |
| 13 |
* @var string |
| 14 |
*/ |
| 15 |
protected static $timezone = 'UTC'; |
| 16 |
|
| 17 |
/** |
| 18 |
* Validate a Timezone name. |
| 19 |
* |
| 20 |
* @param string $timezone Time zone (e.g. 'Europe/London') |
| 21 |
* |
| 22 |
* @return bool Success or failure |
| 23 |
*/ |
| 24 |
private static function validateTimeZone($timezone) |
| 25 |
{ |
| 26 |
return in_array($timezone, DateTimeZone::listIdentifiers()); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Set the Default Timezone used for date/time conversions. |
| 31 |
* |
| 32 |
* @param string $timezone Time zone (e.g. 'Europe/London') |
| 33 |
* |
| 34 |
* @return bool Success or failure |
| 35 |
*/ |
| 36 |
public static function setTimeZone($timezone) |
| 37 |
{ |
| 38 |
if (self::validateTimezone($timezone)) { |
| 39 |
self::$timezone = $timezone; |
| 40 |
|
| 41 |
return true; |
| 42 |
} |
| 43 |
|
| 44 |
return false; |
| 45 |
} |
| 46 |
|
| 47 |
/** |
| 48 |
* Return the Default Timezone used for date/time conversions. |
| 49 |
* |
| 50 |
* @return string Timezone (e.g. 'Europe/London') |
| 51 |
*/ |
| 52 |
public static function getTimeZone() |
| 53 |
{ |
| 54 |
return self::$timezone; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Return the Timezone offset used for date/time conversions to/from UST |
| 59 |
* This requires both the timezone and the calculated date/time to allow for local DST. |
| 60 |
* |
| 61 |
* @param string $timezone The timezone for finding the adjustment to UST |
| 62 |
* @param int $timestamp PHP date/time value |
| 63 |
* |
| 64 |
* @throws PhpSpreadsheetException |
| 65 |
* |
| 66 |
* @return int Number of seconds for timezone adjustment |
| 67 |
*/ |
| 68 |
public static function getTimeZoneAdjustment($timezone, $timestamp) |
| 69 |
{ |
| 70 |
if ($timezone !== null) { |
| 71 |
if (!self::validateTimezone($timezone)) { |
| 72 |
throw new PhpSpreadsheetException('Invalid timezone ' . $timezone); |
| 73 |
} |
| 74 |
} else { |
| 75 |
$timezone = self::$timezone; |
| 76 |
} |
| 77 |
|
| 78 |
if ($timezone == 'UST') { |
| 79 |
return 0; |
| 80 |
} |
| 81 |
|
| 82 |
$objTimezone = new DateTimeZone($timezone); |
| 83 |
$transitions = $objTimezone->getTransitions($timestamp, $timestamp); |
| 84 |
|
| 85 |
return (count($transitions) > 0) ? $transitions[0]['offset'] : 0; |
| 86 |
} |
| 87 |
} |
| 88 |
|