TimeZone.php 2.2 KB

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