Date.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. <?php
  2. namespace Typecho;
  3. /**
  4. * 日期处理
  5. *
  6. * @author qining
  7. * @category typecho
  8. * @package Date
  9. */
  10. class Date
  11. {
  12. /**
  13. * 期望时区偏移
  14. *
  15. * @access public
  16. * @var integer
  17. */
  18. public static $timezoneOffset = 0;
  19. /**
  20. * 服务器时区偏移
  21. *
  22. * @access public
  23. * @var integer
  24. */
  25. public static $serverTimezoneOffset = 0;
  26. /**
  27. * 当前的服务器时间戳
  28. *
  29. * @access public
  30. * @var integer
  31. */
  32. public static $serverTimeStamp;
  33. /**
  34. * 可以被直接转换的时间戳
  35. *
  36. * @access public
  37. * @var integer
  38. */
  39. public $timeStamp = 0;
  40. /**
  41. * @var string
  42. */
  43. public $year;
  44. /**
  45. * @var string
  46. */
  47. public $month;
  48. /**
  49. * @var string
  50. */
  51. public $day;
  52. /**
  53. * 初始化参数
  54. *
  55. * @param integer|null $time 时间戳
  56. */
  57. public function __construct(?int $time = null)
  58. {
  59. $this->timeStamp = (null === $time ? self::time() : $time)
  60. + (self::$timezoneOffset - self::$serverTimezoneOffset);
  61. $this->year = date('Y', $this->timeStamp);
  62. $this->month = date('m', $this->timeStamp);
  63. $this->day = date('d', $this->timeStamp);
  64. }
  65. /**
  66. * 设置当前期望的时区偏移
  67. *
  68. * @param integer $offset
  69. */
  70. public static function setTimezoneOffset(int $offset)
  71. {
  72. self::$timezoneOffset = $offset;
  73. self::$serverTimezoneOffset = idate('Z');
  74. }
  75. /**
  76. * 获取格式化时间
  77. *
  78. * @param string $format 时间格式
  79. * @return string
  80. */
  81. public function format(string $format): string
  82. {
  83. return date($format, $this->timeStamp);
  84. }
  85. /**
  86. * 获取国际化偏移时间
  87. *
  88. * @return string
  89. */
  90. public function word(): string
  91. {
  92. return I18n::dateWord($this->timeStamp, self::time() + (self::$timezoneOffset - self::$serverTimezoneOffset));
  93. }
  94. /**
  95. * 获取GMT时间
  96. *
  97. * @deprecated
  98. * @return int
  99. */
  100. public static function gmtTime(): int
  101. {
  102. return self::time();
  103. }
  104. /**
  105. * 获取服务器时间
  106. *
  107. * @return int
  108. */
  109. public static function time(): int
  110. {
  111. return self::$serverTimeStamp ?: (self::$serverTimeStamp = time());
  112. }
  113. }