DateUtils.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. /**
  3. * Utilities for parsing and formatting dates.
  4. *
  5. * <p>
  6. * Note that this class doesn't use static methods because of the
  7. * synchronization issues with SimpleDateFormat. This lets synchronization be
  8. * done on a per-object level, instead of on a per-class level.
  9. */
  10. class DateUtils
  11. {
  12. /**
  13. * Alternate ISO 8601 format without fractional seconds
  14. */
  15. const ALTERNATE_ISO8601_DATE_FORMAT = "Y-m-d\TH:i:s\Z";
  16. /**
  17. * @var \DateTimeZone The UTC timezone object.
  18. */
  19. public static $UTC_TIMEZONE;
  20. /**
  21. * Initialize $UTC_TIMEZONE
  22. */
  23. public static function __init()
  24. {
  25. DateUtils::$UTC_TIMEZONE = new \DateTimeZone("UTC");
  26. }
  27. /**
  28. * Parses the specified date string as an ISO 8601 date and returns the Date
  29. * object.
  30. *
  31. * @param $dateString string The date string to parse.
  32. * @return \DateTime The parsed Date object.
  33. * @throws \Exception If the date string could not be parsed.
  34. */
  35. public static function parseAlternateIso8601Date($dateString)
  36. {
  37. return \DateTime::createFromFormat(
  38. DateUtils::ALTERNATE_ISO8601_DATE_FORMAT,
  39. $dateString,
  40. DateUtils::$UTC_TIMEZONE
  41. );
  42. }
  43. /**
  44. * Formats the specified date as an ISO 8601 string.
  45. *
  46. * @param $datetime \DateTime The date to format.
  47. * @return string The ISO 8601 string representing the specified date.
  48. */
  49. public static function formatAlternateIso8601Date($datetime)
  50. {
  51. return $datetime->format(DateUtils::ALTERNATE_ISO8601_DATE_FORMAT);
  52. }
  53. /**
  54. * Parses the specified date string as an RFC 822 date and returns the Date object.
  55. *
  56. * @param $dateString string The date string to parse.
  57. * @return \DateTime The parsed Date object.
  58. * @throws \Exception If the date string could not be parsed.
  59. */
  60. public static function parseRfc822Date($dateString)
  61. {
  62. return \DateTime::createFromFormat(
  63. \DateTime::RFC822,
  64. $dateString,
  65. DateUtils::$UTC_TIMEZONE
  66. );
  67. }
  68. /**
  69. * Formats the specified date as an RFC 822 string.
  70. *
  71. * @param $datetime \DateTime The date to format.
  72. * @return string The RFC 822 string representing the specified date.
  73. */
  74. public static function formatRfc822Date($datetime)
  75. {
  76. return $datetime->format(\DateTime::RFC822);
  77. }
  78. }
  79. DateUtils::__init();