DateTime.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Stdlib;
  7. /**
  8. * Converter of date formats
  9. * Internal dates
  10. *
  11. * @api
  12. * @since 100.0.2
  13. */
  14. class DateTime
  15. {
  16. /**#@+
  17. * Date format, used as default. Compatible with \DateTime
  18. */
  19. const DATETIME_INTERNAL_FORMAT = 'yyyy-MM-dd HH:mm:ss';
  20. const DATE_INTERNAL_FORMAT = 'yyyy-MM-dd';
  21. const DATETIME_PHP_FORMAT = 'Y-m-d H:i:s';
  22. const DATE_PHP_FORMAT = 'Y-m-d';
  23. /**#@-*/
  24. /**
  25. * Minimum allowed year value
  26. */
  27. const YEAR_MIN_VALUE = -10000;
  28. /**
  29. * Maximum allowed year value
  30. */
  31. const YEAR_MAX_VALUE = 10000;
  32. /**
  33. * Format date to internal format
  34. *
  35. * @param string|\DateTimeInterface|bool|null $date
  36. * @param boolean $includeTime
  37. * @return string|null
  38. * @api
  39. */
  40. public function formatDate($date, $includeTime = true)
  41. {
  42. if ($date instanceof \DateTimeInterface) {
  43. $format = $includeTime ? self::DATETIME_PHP_FORMAT : self::DATE_PHP_FORMAT;
  44. return $date->format($format);
  45. } elseif (empty($date)) {
  46. return null;
  47. } elseif ($date === true) {
  48. $date = (new \DateTime())->getTimestamp();
  49. } elseif (!is_numeric($date)) {
  50. $date = (new \DateTime($date))->getTimestamp();
  51. }
  52. $format = $includeTime ? self::DATETIME_PHP_FORMAT : self::DATE_PHP_FORMAT;
  53. return (new \DateTime())->setTimestamp($date)->format($format);
  54. }
  55. /**
  56. * Check whether sql date is empty
  57. *
  58. * @param string $date
  59. * @return boolean
  60. */
  61. public function isEmptyDate($date)
  62. {
  63. return preg_replace('#[ 0:-]#', '', $date) === '';
  64. }
  65. /**
  66. * Wrapper for native gmdate function
  67. *
  68. * @param string $format
  69. * @param int $time
  70. * @return string The given time in given format
  71. *
  72. * @deprecated 101.0.1
  73. * @see Use Intl library for datetime handling: http://php.net/manual/en/book.intl.php
  74. *
  75. * @codeCoverageIgnore
  76. */
  77. public function gmDate($format, $time)
  78. {
  79. return gmdate($format, $time);
  80. }
  81. /**
  82. * Wrapper for native strtotime function
  83. *
  84. * @param string $timeStr
  85. * @return int
  86. *
  87. * @deprecated 101.0.1
  88. * @see Use Intl library for datetime handling: http://php.net/manual/en/book.intl.php
  89. *
  90. * @codeCoverageIgnore
  91. */
  92. public function strToTime($timeStr)
  93. {
  94. return strtotime($timeStr);
  95. }
  96. }