Date.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. <?php
  2. /**
  3. * Date helper.
  4. *
  5. * @package Kohana
  6. * @category Helpers
  7. * @author Kohana Team
  8. * @copyright (c) Kohana Team
  9. * @license https://koseven.ga/LICENSE.md
  10. */
  11. class Kohana_Date {
  12. // Second amounts for various time increments
  13. const YEAR = 31556926;
  14. const MONTH = 2629744;
  15. const WEEK = 604800;
  16. const DAY = 86400;
  17. const HOUR = 3600;
  18. const MINUTE = 60;
  19. // Available formats for Date::months()
  20. const MONTHS_LONG = '%B';
  21. const MONTHS_SHORT = '%b';
  22. /**
  23. * Default timestamp format for formatted_time
  24. * @var string
  25. */
  26. public static $timestamp_format = 'Y-m-d H:i:s';
  27. /**
  28. * Timezone for formatted_time
  29. * @link http://uk2.php.net/manual/en/timezones.php
  30. * @var string
  31. */
  32. public static $timezone;
  33. /**
  34. * Returns the offset (in seconds) between two time zones. Use this to
  35. * display dates to users in different time zones.
  36. *
  37. * $seconds = Date::offset('America/Chicago', 'GMT');
  38. *
  39. * [!!] A list of time zones that PHP supports can be found at
  40. * <http://php.net/timezones>.
  41. *
  42. * @param string $remote timezone that to find the offset of
  43. * @param string $local timezone used as the baseline
  44. * @param mixed $now UNIX timestamp or date string
  45. * @return integer
  46. */
  47. public static function offset($remote, $local = NULL, $now = NULL)
  48. {
  49. if ($local === NULL)
  50. {
  51. // Use the default timezone
  52. $local = date_default_timezone_get();
  53. }
  54. if (is_int($now))
  55. {
  56. // Convert the timestamp into a string
  57. $now = date(DateTime::RFC2822, $now);
  58. }
  59. // Create timezone objects
  60. $zone_remote = new DateTimeZone($remote);
  61. $zone_local = new DateTimeZone($local);
  62. // Create date objects from timezones
  63. $time_remote = new DateTime($now, $zone_remote);
  64. $time_local = new DateTime($now, $zone_local);
  65. // Find the offset
  66. $offset = $zone_remote->getOffset($time_remote) - $zone_local->getOffset($time_local);
  67. return $offset;
  68. }
  69. /**
  70. * Number of seconds in a minute, incrementing by a step. Typically used as
  71. * a shortcut for generating a list that can used in a form.
  72. *
  73. * $seconds = Date::seconds(); // 01, 02, 03, ..., 58, 59, 60
  74. *
  75. * @param integer $step amount to increment each step by, 1 to 30
  76. * @param integer $start start value
  77. * @param integer $end end value
  78. * @return array A mirrored (foo => foo) array from 1-60.
  79. */
  80. public static function seconds($step = 1, $start = 0, $end = 60)
  81. {
  82. // Always integer
  83. $step = (int) $step;
  84. $seconds = [];
  85. for ($i = $start; $i < $end; $i += $step)
  86. {
  87. $seconds[$i] = sprintf('%02d', $i);
  88. }
  89. return $seconds;
  90. }
  91. /**
  92. * Number of minutes in an hour, incrementing by a step. Typically used as
  93. * a shortcut for generating a list that can be used in a form.
  94. *
  95. * $minutes = Date::minutes(); // 05, 10, 15, ..., 50, 55, 60
  96. *
  97. * @uses Date::seconds
  98. * @param integer $step amount to increment each step by, 1 to 30
  99. * @return array A mirrored (foo => foo) array from 1-60.
  100. */
  101. public static function minutes($step = 5)
  102. {
  103. // Because there are the same number of minutes as seconds in this set,
  104. // we choose to re-use seconds(), rather than creating an entirely new
  105. // function. Shhhh, it's cheating! ;) There are several more of these
  106. // in the following methods.
  107. return Date::seconds($step);
  108. }
  109. /**
  110. * Number of hours in a day. Typically used as a shortcut for generating a
  111. * list that can be used in a form.
  112. *
  113. * $hours = Date::hours(); // 01, 02, 03, ..., 10, 11, 12
  114. *
  115. * @param integer $step amount to increment each step by
  116. * @param boolean $long use 24-hour time
  117. * @param integer $start the hour to start at
  118. * @return array A mirrored (foo => foo) array from start-12 or start-23.
  119. */
  120. public static function hours($step = 1, $long = FALSE, $start = NULL)
  121. {
  122. // Default values
  123. $step = (int) $step;
  124. $long = (bool) $long;
  125. $hours = [];
  126. // Set the default start if none was specified.
  127. if ($start === NULL)
  128. {
  129. $start = ($long === FALSE) ? 1 : 0;
  130. }
  131. $hours = [];
  132. // 24-hour time has 24 hours, instead of 12
  133. $size = ($long === TRUE) ? 23 : 12;
  134. for ($i = $start; $i <= $size; $i += $step)
  135. {
  136. $hours[$i] = (string) $i;
  137. }
  138. return $hours;
  139. }
  140. /**
  141. * Returns AM or PM, based on a given hour (in 24 hour format).
  142. *
  143. * $type = Date::ampm(12); // PM
  144. * $type = Date::ampm(1); // AM
  145. *
  146. * @param integer $hour number of the hour
  147. * @return string
  148. */
  149. public static function ampm($hour)
  150. {
  151. // Always integer
  152. $hour = (int) $hour;
  153. return ($hour > 11) ? 'PM' : 'AM';
  154. }
  155. /**
  156. * Adjusts a non-24-hour number into a 24-hour number.
  157. *
  158. * $hour = Date::adjust(3, 'pm'); // 15
  159. *
  160. * @param integer $hour hour to adjust
  161. * @param string $ampm AM or PM
  162. * @return string
  163. */
  164. public static function adjust($hour, $ampm)
  165. {
  166. $hour = (int) $hour;
  167. $ampm = strtolower($ampm);
  168. switch ($ampm)
  169. {
  170. case 'am':
  171. if ($hour == 12)
  172. {
  173. $hour = 0;
  174. }
  175. break;
  176. case 'pm':
  177. if ($hour < 12)
  178. {
  179. $hour += 12;
  180. }
  181. break;
  182. }
  183. return sprintf('%02d', $hour);
  184. }
  185. /**
  186. * Number of days in a given month and year. Typically used as a shortcut
  187. * for generating a list that can be used in a form.
  188. *
  189. * Date::days(4, 2010); // 1, 2, 3, ..., 28, 29, 30
  190. *
  191. * @param integer $month number of month
  192. * @param integer $year number of year to check month, defaults to the current year
  193. * @return array A mirrored (foo => foo) array of the days.
  194. */
  195. public static function days($month, $year = FALSE)
  196. {
  197. static $months;
  198. if ($year === FALSE)
  199. {
  200. // Use the current year by default
  201. $year = date('Y');
  202. }
  203. // Always integers
  204. $month = (int) $month;
  205. $year = (int) $year;
  206. // We use caching for months, because time functions are used
  207. if (empty($months[$year][$month]))
  208. {
  209. $months[$year][$month] = [];
  210. // Use date to find the number of days in the given month
  211. $total = date('t', mktime(1, 0, 0, $month, 1, $year)) + 1;
  212. for ($i = 1; $i < $total; $i++)
  213. {
  214. $months[$year][$month][$i] = (string) $i;
  215. }
  216. }
  217. return $months[$year][$month];
  218. }
  219. /**
  220. * Number of months in a year. Typically used as a shortcut for generating
  221. * a list that can be used in a form.
  222. *
  223. * By default a mirrored array of $month_number => $month_number is returned
  224. *
  225. * Date::months();
  226. * // aray(1 => 1, 2 => 2, 3 => 3, ..., 12 => 12)
  227. *
  228. * But you can customise this by passing in either Date::MONTHS_LONG
  229. *
  230. * Date::months(Date::MONTHS_LONG);
  231. * // array(1 => 'January', 2 => 'February', ..., 12 => 'December')
  232. *
  233. * Or Date::MONTHS_SHORT
  234. *
  235. * Date::months(Date::MONTHS_SHORT);
  236. * // array(1 => 'Jan', 2 => 'Feb', ..., 12 => 'Dec')
  237. *
  238. * @uses Date::hours
  239. * @param string $format The format to use for months
  240. * @return array An array of months based on the specified format
  241. */
  242. public static function months($format = NULL)
  243. {
  244. $months = [];
  245. if ($format === Date::MONTHS_LONG OR $format === Date::MONTHS_SHORT)
  246. {
  247. if ( version_compare(PHP_VERSION, '8.1', '<') )
  248. {
  249. $parser = function($time) use ($format) {
  250. return strftime($format, $time);
  251. };
  252. }
  253. elseif ( extension_loaded('intl') )
  254. {
  255. $parser = function($time) use ($format)
  256. {
  257. $formatter = new \IntlDateFormatter(null);
  258. $formatter->setPattern($format === Date::MONTHS_LONG ? 'MMMM' : 'MMM');
  259. return $formatter->format($time);
  260. };
  261. }
  262. else
  263. {
  264. $parser = function($time) use ($format)
  265. {
  266. return date($format === Date::MONTHS_LONG ? 'F' : 'M', $time);
  267. };
  268. }
  269. for ( $i = 1; $i <= 12; ++$i )
  270. {
  271. $months[$i] = $parser(mktime(0, 0, 0, $i, 1));
  272. }
  273. }
  274. else
  275. {
  276. $months = Date::hours();
  277. }
  278. return $months;
  279. }
  280. /**
  281. * Returns an array of years between a starting and ending year. By default,
  282. * the the current year - 5 and current year + 5 will be used. Typically used
  283. * as a shortcut for generating a list that can be used in a form.
  284. *
  285. * $years = Date::years(2000, 2010); // 2000, 2001, ..., 2009, 2010
  286. *
  287. * @param integer $start starting year (default is current year - 5)
  288. * @param integer $end ending year (default is current year + 5)
  289. * @return array
  290. */
  291. public static function years($start = FALSE, $end = FALSE)
  292. {
  293. // Default values
  294. $start = ($start === FALSE) ? (date('Y') - 5) : (int) $start;
  295. $end = ($end === FALSE) ? (date('Y') + 5) : (int) $end;
  296. $years = [];
  297. for ($i = $start; $i <= $end; $i++)
  298. {
  299. $years[$i] = (string) $i;
  300. }
  301. return $years;
  302. }
  303. /**
  304. * Returns time difference between two timestamps, in human readable format.
  305. * If the second timestamp is not given, the current time will be used.
  306. * Also consider using [Date::fuzzy_span] when displaying a span.
  307. *
  308. * $span = Date::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2)
  309. * $span = Date::span(60, 182, 'minutes'); // 2
  310. *
  311. * @param integer $remote timestamp to find the span of
  312. * @param integer $local timestamp to use as the baseline
  313. * @param string $output formatting string
  314. * @return string when only a single output is requested
  315. * @return array associative list of all outputs requested
  316. */
  317. public static function span($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds')
  318. {
  319. // Normalize output
  320. $output = trim(strtolower( (string) $output));
  321. if ( ! $output)
  322. {
  323. // Invalid output
  324. return FALSE;
  325. }
  326. // Array with the output formats
  327. $output = preg_split('/[^a-z]+/', $output);
  328. // Convert the list of outputs to an associative array
  329. $output = array_combine($output, array_fill(0, count($output), 0));
  330. // Make the output values into keys
  331. extract(array_flip($output), EXTR_SKIP);
  332. if ($local === NULL)
  333. {
  334. // Calculate the span from the current time
  335. $local = time();
  336. }
  337. // Calculate timespan (seconds)
  338. $timespan = abs($remote - $local);
  339. if (isset($output['years']))
  340. {
  341. $timespan -= Date::YEAR * ($output['years'] = (int) floor($timespan / Date::YEAR));
  342. }
  343. if (isset($output['months']))
  344. {
  345. $timespan -= Date::MONTH * ($output['months'] = (int) floor($timespan / Date::MONTH));
  346. }
  347. if (isset($output['weeks']))
  348. {
  349. $timespan -= Date::WEEK * ($output['weeks'] = (int) floor($timespan / Date::WEEK));
  350. }
  351. if (isset($output['days']))
  352. {
  353. $timespan -= Date::DAY * ($output['days'] = (int) floor($timespan / Date::DAY));
  354. }
  355. if (isset($output['hours']))
  356. {
  357. $timespan -= Date::HOUR * ($output['hours'] = (int) floor($timespan / Date::HOUR));
  358. }
  359. if (isset($output['minutes']))
  360. {
  361. $timespan -= Date::MINUTE * ($output['minutes'] = (int) floor($timespan / Date::MINUTE));
  362. }
  363. // Seconds ago, 1
  364. if (isset($output['seconds']))
  365. {
  366. $output['seconds'] = $timespan;
  367. }
  368. if (count($output) === 1)
  369. {
  370. // Only a single output was requested, return it
  371. return array_pop($output);
  372. }
  373. // Return array
  374. return $output;
  375. }
  376. /**
  377. * Returns the difference between a time and now in a "fuzzy" way.
  378. * Displaying a fuzzy time instead of a date is usually faster to read and understand.
  379. *
  380. * $span = Date::fuzzy_span(time() - 10); // "moments ago"
  381. * $span = Date::fuzzy_span(time() + 20); // "in moments"
  382. *
  383. * A second parameter is available to manually set the "local" timestamp,
  384. * however this parameter shouldn't be needed in normal usage and is only
  385. * included for unit tests
  386. *
  387. * @param integer $timestamp "remote" timestamp
  388. * @param integer $local_timestamp "local" timestamp, defaults to time()
  389. * @return string
  390. */
  391. public static function fuzzy_span($timestamp, $local_timestamp = NULL)
  392. {
  393. $local_timestamp = ($local_timestamp === NULL) ? time() : (int) $local_timestamp;
  394. // Determine the difference in seconds
  395. $offset = abs($local_timestamp - $timestamp);
  396. if ($offset <= Date::MINUTE)
  397. {
  398. $span = 'moments';
  399. }
  400. elseif ($offset < (Date::MINUTE * 20))
  401. {
  402. $span = 'a few minutes';
  403. }
  404. elseif ($offset < Date::HOUR)
  405. {
  406. $span = 'less than an hour';
  407. }
  408. elseif ($offset < (Date::HOUR * 4))
  409. {
  410. $span = 'a couple of hours';
  411. }
  412. elseif ($offset < Date::DAY)
  413. {
  414. $span = 'less than a day';
  415. }
  416. elseif ($offset < (Date::DAY * 2))
  417. {
  418. $span = 'about a day';
  419. }
  420. elseif ($offset < (Date::DAY * 4))
  421. {
  422. $span = 'a couple of days';
  423. }
  424. elseif ($offset < Date::WEEK)
  425. {
  426. $span = 'less than a week';
  427. }
  428. elseif ($offset < (Date::WEEK * 2))
  429. {
  430. $span = 'about a week';
  431. }
  432. elseif ($offset < Date::MONTH)
  433. {
  434. $span = 'less than a month';
  435. }
  436. elseif ($offset < (Date::MONTH * 2))
  437. {
  438. $span = 'about a month';
  439. }
  440. elseif ($offset < (Date::MONTH * 4))
  441. {
  442. $span = 'a couple of months';
  443. }
  444. elseif ($offset < Date::YEAR)
  445. {
  446. $span = 'less than a year';
  447. }
  448. elseif ($offset < (Date::YEAR * 2))
  449. {
  450. $span = 'about a year';
  451. }
  452. elseif ($offset < (Date::YEAR * 4))
  453. {
  454. $span = 'a couple of years';
  455. }
  456. elseif ($offset < (Date::YEAR * 8))
  457. {
  458. $span = 'a few years';
  459. }
  460. elseif ($offset < (Date::YEAR * 12))
  461. {
  462. $span = 'about a decade';
  463. }
  464. elseif ($offset < (Date::YEAR * 24))
  465. {
  466. $span = 'a couple of decades';
  467. }
  468. elseif ($offset < (Date::YEAR * 64))
  469. {
  470. $span = 'several decades';
  471. }
  472. else
  473. {
  474. $span = 'a long time';
  475. }
  476. if ($timestamp <= $local_timestamp)
  477. {
  478. // This is in the past
  479. return $span.' ago';
  480. }
  481. else
  482. {
  483. // This in the future
  484. return 'in '.$span;
  485. }
  486. }
  487. /**
  488. * Converts a UNIX timestamp to DOS format. There are very few cases where
  489. * this is needed, but some binary formats use it (eg: zip files.)
  490. * Converting the other direction is done using {@link Date::dos2unix}.
  491. *
  492. * $dos = Date::unix2dos($unix);
  493. *
  494. * @param integer $timestamp UNIX timestamp
  495. * @return integer
  496. */
  497. public static function unix2dos($timestamp = FALSE)
  498. {
  499. $timestamp = ($timestamp === FALSE) ? getdate() : getdate($timestamp);
  500. if ($timestamp['year'] < 1980)
  501. {
  502. return (1 << 21 | 1 << 16);
  503. }
  504. $timestamp['year'] -= 1980;
  505. // What voodoo is this? I have no idea... Geert can explain it though,
  506. // and that's good enough for me.
  507. return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 |
  508. $timestamp['mday'] << 16 | $timestamp['hours'] << 11 |
  509. $timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1);
  510. }
  511. /**
  512. * Converts a DOS timestamp to UNIX format.There are very few cases where
  513. * this is needed, but some binary formats use it (eg: zip files.)
  514. * Converting the other direction is done using {@link Date::unix2dos}.
  515. *
  516. * $unix = Date::dos2unix($dos);
  517. *
  518. * @param integer $timestamp DOS timestamp
  519. * @return integer
  520. */
  521. public static function dos2unix($timestamp = FALSE)
  522. {
  523. $sec = 2 * ($timestamp & 0x1f);
  524. $min = ($timestamp >> 5) & 0x3f;
  525. $hrs = ($timestamp >> 11) & 0x1f;
  526. $day = ($timestamp >> 16) & 0x1f;
  527. $mon = ($timestamp >> 21) & 0x0f;
  528. $year = ($timestamp >> 25) & 0x7f;
  529. return mktime($hrs, $min, $sec, $mon, $day, $year + 1980);
  530. }
  531. /**
  532. * Returns a date/time string with the specified timestamp format
  533. *
  534. * $time = Date::formatted_time('5 minutes ago');
  535. *
  536. * @link http://www.php.net/manual/datetime.construct
  537. * @param string $datetime_str datetime string
  538. * @param string $timestamp_format timestamp format
  539. * @param string $timezone timezone identifier
  540. * @return string
  541. */
  542. public static function formatted_time($datetime_str = 'now', $timestamp_format = NULL, $timezone = NULL)
  543. {
  544. $timestamp_format = ($timestamp_format == NULL) ? Date::$timestamp_format : $timestamp_format;
  545. $timezone = ($timezone === NULL) ? Date::$timezone : $timezone;
  546. $tz = new DateTimeZone($timezone ? $timezone : date_default_timezone_get());
  547. $time = new DateTime($datetime_str, $tz);
  548. // Convert the time back to the expected timezone if required (in case the datetime_str provided a timezone,
  549. // offset or unix timestamp. This also ensures that the timezone reported by the object is correct on HHVM
  550. // (see https://github.com/facebook/hhvm/issues/2302).
  551. $time->setTimeZone($tz);
  552. return $time->format($timestamp_format);
  553. }
  554. }