fork(8) download
  1. <?php
  2.  
  3. $tz = new DateTimeZoneEx('America/New_York');
  4.  
  5. echo "\nTesting isValidTime:\n";
  6.  
  7. $dates = [
  8. '2013-03-10 01:59:59',
  9. '2013-03-10 02:00:00',
  10. '2013-03-10 02:59:59',
  11. '2013-03-10 03:00:00',
  12. ];
  13.  
  14. foreach ($dates as $date) {
  15. $result = $tz->isValidTime(new DateTime($date, $tz));
  16. echo "isValidTime($date) = ".($result ? "true" : "false")."\n";
  17. }
  18.  
  19. echo "\nTesting isAmbiguousTime:\n";
  20.  
  21. $dates = [
  22. '2013-11-03 00:59:59',
  23. '2013-11-03 01:00:00',
  24. '2013-11-03 01:59:59',
  25. '2013-11-03 02:00:00',
  26. ];
  27.  
  28. foreach ($dates as $date) {
  29. $result = $tz->isAmbiguousTime(new DateTime($date, $tz));
  30. echo "isAmbiguousTime($date) = ".($result ? "true" : "false")."\n";
  31. }
  32.  
  33.  
  34. class DateTimeZoneEx extends DateTimeZone
  35. {
  36. const MAX_DST_SHIFT = 7200; // let's be generous
  37.  
  38. public function isValidTime(DateTime $date)
  39. {
  40.  
  41. $ts = $date->getTimestamp();
  42. $transitions = $this->getTransitions($ts - self::MAX_DST_SHIFT, $ts + self::MAX_DST_SHIFT);
  43.  
  44. if (count($transitions) == 1) {
  45. return true;
  46. }
  47.  
  48. $shift = $transitions[1]['offset'] - $transitions[0]['offset'];
  49.  
  50. if ($shift < 0) {
  51. return true;
  52. }
  53.  
  54. $compare = new DateTime($date->format('Y-m-d H:i:s'), $this);
  55.  
  56. return $compare->modify("$shift seconds")->getTimestamp() != $ts;
  57. }
  58.  
  59. public function isAmbiguousTime(DateTime $date)
  60. {
  61. $ts = $date->getTimestamp();
  62. $transitions = $this->getTransitions($ts - self::MAX_DST_SHIFT, $ts + self::MAX_DST_SHIFT);
  63.  
  64. if (count($transitions) == 1) {
  65. return false;
  66. }
  67.  
  68. $shift = $transitions[1]['offset'] - $transitions[0]['offset'];
  69.  
  70. if ($shift > 0) {
  71. return false;
  72. }
  73.  
  74. $shift = -$shift;
  75. $compare = new DateTime($date->format('Y-m-d H:i:s'), $this);
  76. return $compare->modify("$shift seconds")->getTimestamp() - $ts > $shift;
  77. }
  78. }
  79.  
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Testing isValidTime:
isValidTime(2013-03-10 01:59:59) = true
isValidTime(2013-03-10 02:00:00) = false
isValidTime(2013-03-10 02:59:59) = false
isValidTime(2013-03-10 03:00:00) = true

Testing isAmbiguousTime:
isAmbiguousTime(2013-11-03 00:59:59) = false
isAmbiguousTime(2013-11-03 01:00:00) = true
isAmbiguousTime(2013-11-03 01:59:59) = true
isAmbiguousTime(2013-11-03 02:00:00) = false