1
0

DateTimeHelper.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. namespace fphammerle\helpers;
  3. class DateTimeHelper
  4. {
  5. const ISO8601_DATE_FORMAT = 'Y-m-d';
  6. const ISO8601_TIME_FORMAT = 'H:i:s';
  7. const _timezone_iso_pattern = '(?P<tz>Z|[\+-]\d{2}.\d{2})';
  8. /**
  9. * @param integer|null $timestamp unix timestamp
  10. * @return \DateTime|null
  11. */
  12. public static function timestampToDateTime($timestamp)
  13. {
  14. if($timestamp === null) {
  15. return null;
  16. } elseif(is_int($timestamp)) {
  17. $dt = new \DateTime();
  18. $dt->setTimestamp($timestamp);
  19. return $dt;
  20. } else {
  21. throw new \InvalidArgumentException('expected integer or null');
  22. }
  23. }
  24. /**
  25. * @param string|null $text
  26. * @return \DatePeriod|null
  27. */
  28. public static function parse($text)
  29. {
  30. if($text === null) {
  31. return null;
  32. } else {
  33. if(preg_match(
  34. '/^(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})'
  35. .'([ T](?P<h>\d{2}):(?P<i>\d{2})(:(?P<s>\d{2}))?)?'
  36. . '(' . self::_timezone_iso_pattern . ')?$/',
  37. $text,
  38. $attr
  39. )) {
  40. $start = new \DateTime($text);
  41. if(!empty($attr['s'])) {
  42. $interval = new \DateInterval('PT1S');
  43. } elseif(!empty($attr['i'])) {
  44. $interval = new \DateInterval('PT1M');
  45. } else {
  46. $interval = new \DateInterval('P1D');
  47. }
  48. return new \DatePeriod($start, $interval, 0);
  49. } elseif(preg_match('/^\d{4}-(?P<m>\d{2})(( (?=-)| ?(?!-))' . self::_timezone_iso_pattern . ')?$/', $text, $attr)) {
  50. return new \DatePeriod(
  51. new \DateTime($text),
  52. new \DateInterval('P1M'),
  53. 0
  54. );
  55. } elseif(preg_match('/^(?P<y>\d{4})( ?' . self::_timezone_iso_pattern . ')?$/', $text, $attr)) {
  56. return new \DatePeriod(
  57. new \DateTime(sprintf(
  58. '%s-01-01 %s',
  59. $attr['y'],
  60. isset($attr['tz']) ? $attr['tz'] : ''
  61. )),
  62. new \DateInterval('P1Y'),
  63. 0
  64. );
  65. } else {
  66. throw new \InvalidArgumentException(
  67. sprintf("could not parse string '%s'", $text)
  68. );
  69. }
  70. }
  71. }
  72. /**
  73. * @param string|null $text
  74. * @return \DateTime|null
  75. */
  76. public static function parseGetStart($text)
  77. {
  78. $period = self::parse($text);
  79. if($period) {
  80. return $period->start;
  81. } else {
  82. return null;
  83. }
  84. }
  85. public static function deinvertInterval(\DateInterval $source = null)
  86. {
  87. // \DateInterval does not implement clone.
  88. // @see https://bugs.php.net/bug.php?id=50559
  89. $result = unserialize(serialize($source));
  90. if($result->invert) {
  91. $result->y *= -1;
  92. $result->m *= -1;
  93. $result->d *= -1;
  94. $result->h *= -1;
  95. $result->i *= -1;
  96. $result->s *= -1;
  97. $result->invert = 0;
  98. }
  99. return $result;
  100. }
  101. /**
  102. * @param \DateInterval|\DatePeriod|null $i
  103. * @return string|null
  104. */
  105. public static function iso($i)
  106. {
  107. if(is_null($i)) {
  108. return null;
  109. } elseif(sizeof(get_object_vars($i)) == 0) {
  110. throw new \InvalidArgumentException(
  111. sprintf("given instance is invalid\n%s", print_r($i, true))
  112. );
  113. } elseif($i instanceof \DateTime) {
  114. return $i->format(\DateTime::ATOM);
  115. } elseif($i instanceof \DateInterval) {
  116. $i = self::deinvertInterval($i);
  117. if($i->y < 0 || $i->m < 0 || $i->d < 0 || $i->h < 0 || $i->i < 0 || $i->s < 0) {
  118. throw new \InvalidArgumentException(
  119. sprintf("negative intervals are not supported\n%s", print_r($i, true))
  120. );
  121. } else {
  122. return StringHelper::prepend('P', StringHelper::unite([
  123. StringHelper::append($i->y ?: null, 'Y'),
  124. StringHelper::append($i->m ?: null, 'M'),
  125. StringHelper::append($i->d ?: null, 'D'),
  126. StringHelper::prepend('T', StringHelper::unite([
  127. StringHelper::append($i->h ?: null, 'H'),
  128. StringHelper::append($i->i ?: null, 'M'),
  129. StringHelper::append($i->s ?: null, 'S'),
  130. ])),
  131. ])) ?: 'P0S';
  132. }
  133. } elseif($i instanceof \DatePeriod) {
  134. // Cave:
  135. // (new \DatePeriod(
  136. // new \DateTime('2016-08-05T14:50:14Z'),
  137. // new \DateInterval('P1D'),
  138. // -1
  139. // )->recurrences == 1
  140. if($i->recurrences <= 0) {
  141. throw new \Exception(
  142. 'conversion of periods with number of occurances'
  143. . ' being negative is not supported'
  144. );
  145. }
  146. $repetitions = -1;
  147. foreach($i as $dt) {
  148. $repetitions++;
  149. // printf("%d. %s\n", $repetitions, $dt->format(\DateTime::ATOM));
  150. }
  151. // \DatePeriod::getStartDate() is available from php 5.6.5.
  152. $start_iso = self::iso($i->start);
  153. // \DatePeriod::getDateInterval() is available from php 5.6.5.
  154. // \DatePeriod::$interval returned an invalid \DatePeriod instance
  155. // in php 7.0.8
  156. $interval_iso = self::iso(get_object_vars($i)['interval']);
  157. switch($repetitions) {
  158. case -1:
  159. // no valid date within period
  160. // e.g. new \DatePeriod(
  161. // new \DateTime('2016-08-05T14:50:14+08:00'),
  162. // new \DateInterval('PT1S'),
  163. // new \DateTime('2016-08-05T14:50:14+08:00')
  164. // )
  165. throw new \InvalidArgumentException(
  166. 'given period does not contain any valid date'
  167. );
  168. case 0:
  169. return sprintf('%s/%s', $start_iso, $interval_iso);
  170. default:
  171. return sprintf('R%d/%s/%s', $repetitions, $start_iso, $interval_iso);
  172. }
  173. } else {
  174. throw new \InvalidArgumentException(sprintf(
  175. "expected \\DateTime, \\DateInterval or \\DatePeriod\n%s",
  176. print_r($i, true)
  177. ));
  178. }
  179. }
  180. }