1
0

DateTimeHelper.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace fphammerle\helpers;
  3. class DateTimeHelper
  4. {
  5. /**
  6. * @param integer|null $timestamp unix timestamp
  7. * @return DateTime|null
  8. */
  9. public static function timestampToDateTime($timestamp)
  10. {
  11. if($timestamp === null) {
  12. return null;
  13. } elseif(is_int($timestamp)) {
  14. $dt = new \DateTime();
  15. $dt->setTimestamp($timestamp);
  16. return $dt;
  17. } else {
  18. throw new \InvalidArgumentException('expected integer or null');
  19. }
  20. }
  21. /**
  22. * @param string|null $text
  23. * @return DatePeriod|null
  24. */
  25. public static function parse($text)
  26. {
  27. if($text === null) {
  28. return null;
  29. } else {
  30. if(preg_match(
  31. '/^(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})'
  32. .'([ T](?P<h>\d{2}):(?P<i>\d{2}):(?P<s>\d{2}))?$/',
  33. $text,
  34. $attr
  35. )) {
  36. $start = new \DateTime();
  37. $start->setDate($attr['y'], $attr['m'], $attr['d']);
  38. $start->setTime(
  39. isset($attr['h']) ? $attr['h'] : 0,
  40. isset($attr['i']) ? $attr['i'] : 0,
  41. isset($attr['s']) ? $attr['s'] : 0
  42. );
  43. if(isset($attr['h'])) {
  44. $interval = new \DateInterval('PT1S');
  45. } else {
  46. $interval = new \DateInterval('P1D');
  47. }
  48. $end = clone $start;
  49. $end->add($interval);
  50. return new \DatePeriod($start, $interval, $end);
  51. } else {
  52. throw new \InvalidArgumentException(
  53. sprintf("could not parse string '%s'", $text)
  54. );
  55. }
  56. }
  57. }
  58. }