Date.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. // | Original reference: https://gitee.com/karson/fastadmin
  12. // +----------------------------------------------------------------------
  13. // +----------------------------------------------------------------------
  14. // | 日期时间类
  15. // +----------------------------------------------------------------------
  16. namespace util;
  17. use DateTime;
  18. use DateTimeZone;
  19. /**
  20. * 日期时间处理类
  21. */
  22. class Date
  23. {
  24. const YEAR = 31536000;
  25. const MONTH = 2592000;
  26. const WEEK = 604800;
  27. const DAY = 86400;
  28. const HOUR = 3600;
  29. const MINUTE = 60;
  30. /**
  31. * 计算两个时区间相差的时长,单位为秒
  32. *
  33. * $seconds = self::offset('America/Chicago', 'GMT');
  34. *
  35. * [!!] A list of time zones that PHP supports can be found at
  36. * <http://php.net/timezones>.
  37. *
  38. * @param string $remote timezone that to find the offset of
  39. * @param string|null $local timezone used as the baseline
  40. * @param int|string|null $now UNIX timestamp or date string
  41. *
  42. * @return int
  43. * @throws \Exception
  44. */
  45. public static function offset(string $remote, ?string $local = null, $now = null): int
  46. {
  47. if ($local === null) {
  48. // Use the default timezone
  49. $local = date_default_timezone_get();
  50. }
  51. if (is_int($now)) {
  52. // Convert the timestamp into a string
  53. $now = date(DateTime::RFC2822, $now);
  54. }
  55. // Create timezone objects
  56. $zone_remote = new DateTimeZone($remote);
  57. $zone_local = new DateTimeZone($local);
  58. // Create date objects from timezones
  59. $time_remote = new DateTime($now, $zone_remote);
  60. $time_local = new DateTime($now, $zone_local);
  61. // Find the offset
  62. return $zone_remote->getOffset($time_remote) - $zone_local->getOffset($time_local);
  63. }
  64. /**
  65. * 计算两个时间戳之间相差的时间
  66. *
  67. * $span = self::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2)
  68. * $span = self::span(60, 182, 'minutes'); // 2
  69. *
  70. * @param int $remote timestamp to find the span of
  71. * @param ?int $local timestamp to use as the baseline
  72. * @param string $output formatting string
  73. * @return string when only a single output is requested
  74. * @return array associative list of all outputs requested
  75. * @from https://github.com/kohana/ohanzee-helpers/blob/master/src/Date.php
  76. */
  77. public static function span(int $remote, ?int $local = null, string $output = 'years,months,weeks,days,hours,minutes,seconds')
  78. {
  79. // Normalize output
  80. $output = trim(strtolower((string) $output));
  81. if (!$output) {
  82. // Invalid output
  83. return false;
  84. }
  85. // Array with the output formats
  86. $output = preg_split('/[^a-z]+/', $output);
  87. // Convert the list of outputs to an associative array
  88. $output = array_combine($output, array_fill(0, count($output), 0));
  89. // Make the output values into keys
  90. extract(array_flip($output), EXTR_SKIP);
  91. if ($local === null) {
  92. // Calculate the span from the current time
  93. $local = time();
  94. }
  95. // Calculate timespan (seconds)
  96. $timespan = abs($remote - $local);
  97. if (isset($output['years'])) {
  98. $timespan -= self::YEAR * ($output['years'] = (int) floor($timespan / self::YEAR));
  99. }
  100. if (isset($output['months'])) {
  101. $timespan -= self::MONTH * ($output['months'] = (int) floor($timespan / self::MONTH));
  102. }
  103. if (isset($output['weeks'])) {
  104. $timespan -= self::WEEK * ($output['weeks'] = (int) floor($timespan / self::WEEK));
  105. }
  106. if (isset($output['days'])) {
  107. $timespan -= self::DAY * ($output['days'] = (int) floor($timespan / self::DAY));
  108. }
  109. if (isset($output['hours'])) {
  110. $timespan -= self::HOUR * ($output['hours'] = (int) floor($timespan / self::HOUR));
  111. }
  112. if (isset($output['minutes'])) {
  113. $timespan -= self::MINUTE * ($output['minutes'] = (int) floor($timespan / self::MINUTE));
  114. }
  115. // Seconds ago, 1
  116. if (isset($output['seconds'])) {
  117. $output['seconds'] = $timespan;
  118. }
  119. if (count($output) === 1) {
  120. // Only a single output was requested, return it
  121. return array_pop($output);
  122. }
  123. // Return array
  124. return $output;
  125. }
  126. /**
  127. * 格式化 UNIX 时间戳为人易读的字符串
  128. * @param int $remote Unix 时间戳
  129. * @param mixed $local 本地时间
  130. * @return string 格式化的日期字符串
  131. */
  132. public static function human(int $remote, $local = null): string
  133. {
  134. $time_diff = (is_null($local) || $local ? time() : $local) - $remote;
  135. $tense = $time_diff < 0 ? '后' : '前';
  136. $time_diff = abs($time_diff);
  137. $chunks = [
  138. [60 * 60 * 24 * 365, '年'],
  139. [60 * 60 * 24 * 30, '月'],
  140. [60 * 60 * 24 * 7, '周'],
  141. [60 * 60 * 24, '天'],
  142. [60 * 60, '小时'],
  143. [60, '分钟'],
  144. [1, '秒'],
  145. ];
  146. $name = 'second';
  147. $count = 0;
  148. for ($i = 0, $j = count($chunks); $i < $j; $i++) {
  149. $seconds = $chunks[$i][0];
  150. $name = $chunks[$i][1];
  151. if (($count = floor($time_diff / $seconds)) != 0) {
  152. break;
  153. }
  154. }
  155. return $count . $name . $tense;
  156. }
  157. /**
  158. * 获取一个基于时间偏移的Unix时间戳
  159. *
  160. * @param string $type 时间类型,默认为day,可选minute,hour,day,week,month,quarter,year
  161. * @param int $offset 时间偏移量 默认为0,正数表示当前type之后,负数表示当前type之前
  162. * @param string $position 时间的开始或结束,默认为begin,可选前(begin,start,first,front),end
  163. * @param ?int $year 基准年,默认为null,即以当前年为基准
  164. * @param ?int $month 基准月,默认为null,即以当前月为基准
  165. * @param ?int $day 基准天,默认为null,即以当前天为基准
  166. * @param ?int $hour 基准小时,默认为null,即以当前年小时基准
  167. * @param ?int $minute 基准分钟,默认为null,即以当前分钟为基准
  168. * @return false|int 处理后的Unix时间戳
  169. */
  170. public static function unixtime(string $type = 'day', int $offset = 0, string $position = 'begin', ?int $year = null, ?int $month = null, ?int $day = null, ?int $hour = null, ?int $minute = null): false | int
  171. {
  172. $year = is_null($year) ? date('Y') : $year;
  173. $month = is_null($month) ? date('m') : $month;
  174. $day = is_null($day) ? date('d') : $day;
  175. $hour = is_null($hour) ? date('H') : $hour;
  176. $minute = is_null($minute) ? date('i') : $minute;
  177. $position = in_array($position, ['begin', 'start', 'first', 'front']);
  178. $baseTime = mktime(0, 0, 0, $month, $day, $year);
  179. switch ($type) {
  180. case 'minute':
  181. $time = $position ? mktime($hour, $minute + $offset, 0, $month, $day, $year) : mktime($hour, $minute + $offset, 59, $month, $day, $year);
  182. break;
  183. case 'hour':
  184. $time = $position ? mktime($hour + $offset, 0, 0, $month, $day, $year) : mktime($hour + $offset, 59, 59, $month, $day, $year);
  185. break;
  186. case 'day':
  187. $time = $position ? mktime(0, 0, 0, $month, $day + $offset, $year) : mktime(23, 59, 59, $month, $day + $offset, $year);
  188. break;
  189. case 'week':
  190. $weekIndex = date("w", $baseTime);
  191. $time = $position ?
  192. strtotime($offset . " weeks", strtotime(date('Y-m-d', strtotime("-" . ($weekIndex ? $weekIndex - 1 : 6) . " days", $baseTime)))) :
  193. strtotime($offset . " weeks", strtotime(date('Y-m-d 23:59:59', strtotime("+" . (6 - ($weekIndex ? $weekIndex - 1 : 6)) . " days", $baseTime))));
  194. break;
  195. case 'month':
  196. $_timestamp = mktime(0, 0, 0, $month + $offset, 1, $year);
  197. $time = $position ? $_timestamp : mktime(23, 59, 59, $month + $offset, self::days_in_month(date("m", $_timestamp), date("Y", $_timestamp)), $year);
  198. break;
  199. case 'quarter':
  200. $quarter = ceil(date('n', $baseTime) / 3) + $offset;
  201. $month = $quarter * 3;
  202. $offset_year = ceil($month / 12) - 1;
  203. $year = $year + $offset_year;
  204. $month = $month - ($offset_year * 12);
  205. $time = $position ?
  206. mktime(0, 0, 0, $month - 2, 1, $year) :
  207. mktime(23, 59, 59, $month, self::days_in_month($month, $year), $year);
  208. break;
  209. case 'year':
  210. $time = $position ? mktime(0, 0, 0, 1, 1, $year + $offset) : mktime(23, 59, 59, 12, 31, $year + $offset);
  211. break;
  212. default:
  213. $time = mktime($hour, $minute, 0, $month, $day, $year);
  214. break;
  215. }
  216. return $time;
  217. }
  218. /**
  219. * 获取指定年月拥有的天数
  220. * @param int $month
  221. * @param int $year
  222. * @return int
  223. */
  224. public static function days_in_month(int $month, int $year): int
  225. {
  226. if (function_exists("cal_days_in_month")) {
  227. return cal_days_in_month(CAL_GREGORIAN, $month, $year);
  228. } else {
  229. return date('t', mktime(0, 0, 0, $month, 1, $year));
  230. }
  231. }
  232. }