class-wc-datetime.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <?php
  2. /**
  3. * WC Wrapper for PHP DateTime which adds support for gmt/utc offset when a
  4. * timezone is absent
  5. *
  6. * @since 3.0.0
  7. * @package WooCommerce/Classes
  8. */
  9. defined( 'ABSPATH' ) || exit;
  10. /**
  11. * Datetime class.
  12. */
  13. class WC_DateTime extends DateTime {
  14. /**
  15. * UTC Offset, if needed. Only used when a timezone is not set. When
  16. * timezones are used this will equal 0.
  17. *
  18. * @var integer
  19. */
  20. protected $utc_offset = 0;
  21. /**
  22. * Output an ISO 8601 date string in local (WordPress) timezone.
  23. *
  24. * @since 3.0.0
  25. * @return string
  26. */
  27. public function __toString() {
  28. return $this->format( DATE_ATOM );
  29. }
  30. /**
  31. * Set UTC offset - this is a fixed offset instead of a timezone.
  32. *
  33. * @param int $offset Offset.
  34. */
  35. public function set_utc_offset( $offset ) {
  36. $this->utc_offset = intval( $offset );
  37. }
  38. /**
  39. * Get UTC offset if set, or default to the DateTime object's offset.
  40. */
  41. public function getOffset() {
  42. if ( $this->utc_offset ) {
  43. return $this->utc_offset;
  44. } else {
  45. return parent::getOffset();
  46. }
  47. }
  48. /**
  49. * Set timezone.
  50. *
  51. * @param DateTimeZone $timezone DateTimeZone instance.
  52. * @return DateTime
  53. */
  54. public function setTimezone( $timezone ) {
  55. $this->utc_offset = 0;
  56. return parent::setTimezone( $timezone );
  57. }
  58. /**
  59. * Missing in PHP 5.2 so just here so it can be supported consistently.
  60. *
  61. * @since 3.0.0
  62. * @return int
  63. */
  64. public function getTimestamp() {
  65. return method_exists( 'DateTime', 'getTimestamp' ) ? parent::getTimestamp() : $this->format( 'U' );
  66. }
  67. /**
  68. * Get the timestamp with the WordPress timezone offset added or subtracted.
  69. *
  70. * @since 3.0.0
  71. * @return int
  72. */
  73. public function getOffsetTimestamp() {
  74. return $this->getTimestamp() + $this->getOffset();
  75. }
  76. /**
  77. * Format a date based on the offset timestamp.
  78. *
  79. * @since 3.0.0
  80. * @param string $format Date format.
  81. * @return string
  82. */
  83. public function date( $format ) {
  84. return gmdate( $format, $this->getOffsetTimestamp() );
  85. }
  86. /**
  87. * Return a localised date based on offset timestamp. Wrapper for date_i18n function.
  88. *
  89. * @since 3.0.0
  90. * @param string $format Date format.
  91. * @return string
  92. */
  93. public function date_i18n( $format = 'Y-m-d' ) {
  94. return date_i18n( $format, $this->getOffsetTimestamp() );
  95. }
  96. }