Date.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  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. for ($i = 1; $i <= 12; ++$i)
  248. {
  249. $months[$i] = strftime($format, mktime(0, 0, 0, $i, 1));
  250. }
  251. }
  252. else
  253. {
  254. $months = Date::hours();
  255. }
  256. return $months;
  257. }
  258. /**
  259. * Returns an array of years between a starting and ending year. By default,
  260. * the the current year - 5 and current year + 5 will be used. Typically used
  261. * as a shortcut for generating a list that can be used in a form.
  262. *
  263. * $years = Date::years(2000, 2010); // 2000, 2001, ..., 2009, 2010
  264. *
  265. * @param integer $start starting year (default is current year - 5)
  266. * @param integer $end ending year (default is current year + 5)
  267. * @return array
  268. */
  269. public static function years($start = FALSE, $end = FALSE)
  270. {
  271. // Default values
  272. $start = ($start === FALSE) ? (date('Y') - 5) : (int) $start;
  273. $end = ($end === FALSE) ? (date('Y') + 5) : (int) $end;
  274. $years = [];
  275. for ($i = $start; $i <= $end; $i++)
  276. {
  277. $years[$i] = (string) $i;
  278. }
  279. return $years;
  280. }
  281. /**
  282. * Returns time difference between two timestamps, in human readable format.
  283. * If the second timestamp is not given, the current time will be used.
  284. * Also consider using [Date::fuzzy_span] when displaying a span.
  285. *
  286. * $span = Date::span(60, 182, 'minutes,seconds'); // array('minutes' => 2, 'seconds' => 2)
  287. * $span = Date::span(60, 182, 'minutes'); // 2
  288. *
  289. * @param integer $remote timestamp to find the span of
  290. * @param integer $local timestamp to use as the baseline
  291. * @param string $output formatting string
  292. * @return string when only a single output is requested
  293. * @return array associative list of all outputs requested
  294. */
  295. public static function span($remote, $local = NULL, $output = 'years,months,weeks,days,hours,minutes,seconds')
  296. {
  297. // Normalize output
  298. $output = trim(strtolower( (string) $output));
  299. if ( ! $output)
  300. {
  301. // Invalid output
  302. return FALSE;
  303. }
  304. // Array with the output formats
  305. $output = preg_split('/[^a-z]+/', $output);
  306. // Convert the list of outputs to an associative array
  307. $output = array_combine($output, array_fill(0, count($output), 0));
  308. // Make the output values into keys
  309. extract(array_flip($output), EXTR_SKIP);
  310. if ($local === NULL)
  311. {
  312. // Calculate the span from the current time
  313. $local = time();
  314. }
  315. // Calculate timespan (seconds)
  316. $timespan = abs($remote - $local);
  317. if (isset($output['years']))
  318. {
  319. $timespan -= Date::YEAR * ($output['years'] = (int) floor($timespan / Date::YEAR));
  320. }
  321. if (isset($output['months']))
  322. {
  323. $timespan -= Date::MONTH * ($output['months'] = (int) floor($timespan / Date::MONTH));
  324. }
  325. if (isset($output['weeks']))
  326. {
  327. $timespan -= Date::WEEK * ($output['weeks'] = (int) floor($timespan / Date::WEEK));
  328. }
  329. if (isset($output['days']))
  330. {
  331. $timespan -= Date::DAY * ($output['days'] = (int) floor($timespan / Date::DAY));
  332. }
  333. if (isset($output['hours']))
  334. {
  335. $timespan -= Date::HOUR * ($output['hours'] = (int) floor($timespan / Date::HOUR));
  336. }
  337. if (isset($output['minutes']))
  338. {
  339. $timespan -= Date::MINUTE * ($output['minutes'] = (int) floor($timespan / Date::MINUTE));
  340. }
  341. // Seconds ago, 1
  342. if (isset($output['seconds']))
  343. {
  344. $output['seconds'] = $timespan;
  345. }
  346. if (count($output) === 1)
  347. {
  348. // Only a single output was requested, return it
  349. return array_pop($output);
  350. }
  351. // Return array
  352. return $output;
  353. }
  354. /**
  355. * Returns the difference between a time and now in a "fuzzy" way.
  356. * Displaying a fuzzy time instead of a date is usually faster to read and understand.
  357. *
  358. * $span = Date::fuzzy_span(time() - 10); // "moments ago"
  359. * $span = Date::fuzzy_span(time() + 20); // "in moments"
  360. *
  361. * A second parameter is available to manually set the "local" timestamp,
  362. * however this parameter shouldn't be needed in normal usage and is only
  363. * included for unit tests
  364. *
  365. * @param integer $timestamp "remote" timestamp
  366. * @param integer $local_timestamp "local" timestamp, defaults to time()
  367. * @return string
  368. */
  369. public static function fuzzy_span($timestamp, $local_timestamp = NULL)
  370. {
  371. $local_timestamp = ($local_timestamp === NULL) ? time() : (int) $local_timestamp;
  372. // Determine the difference in seconds
  373. $offset = abs($local_timestamp - $timestamp);
  374. if ($offset <= Date::MINUTE)
  375. {
  376. $span = 'moments';
  377. }
  378. elseif ($offset < (Date::MINUTE * 20))
  379. {
  380. $span = 'a few minutes';
  381. }
  382. elseif ($offset < Date::HOUR)
  383. {
  384. $span = 'less than an hour';
  385. }
  386. elseif ($offset < (Date::HOUR * 4))
  387. {
  388. $span = 'a couple of hours';
  389. }
  390. elseif ($offset < Date::DAY)
  391. {
  392. $span = 'less than a day';
  393. }
  394. elseif ($offset < (Date::DAY * 2))
  395. {
  396. $span = 'about a day';
  397. }
  398. elseif ($offset < (Date::DAY * 4))
  399. {
  400. $span = 'a couple of days';
  401. }
  402. elseif ($offset < Date::WEEK)
  403. {
  404. $span = 'less than a week';
  405. }
  406. elseif ($offset < (Date::WEEK * 2))
  407. {
  408. $span = 'about a week';
  409. }
  410. elseif ($offset < Date::MONTH)
  411. {
  412. $span = 'less than a month';
  413. }
  414. elseif ($offset < (Date::MONTH * 2))
  415. {
  416. $span = 'about a month';
  417. }
  418. elseif ($offset < (Date::MONTH * 4))
  419. {
  420. $span = 'a couple of months';
  421. }
  422. elseif ($offset < Date::YEAR)
  423. {
  424. $span = 'less than a year';
  425. }
  426. elseif ($offset < (Date::YEAR * 2))
  427. {
  428. $span = 'about a year';
  429. }
  430. elseif ($offset < (Date::YEAR * 4))
  431. {
  432. $span = 'a couple of years';
  433. }
  434. elseif ($offset < (Date::YEAR * 8))
  435. {
  436. $span = 'a few years';
  437. }
  438. elseif ($offset < (Date::YEAR * 12))
  439. {
  440. $span = 'about a decade';
  441. }
  442. elseif ($offset < (Date::YEAR * 24))
  443. {
  444. $span = 'a couple of decades';
  445. }
  446. elseif ($offset < (Date::YEAR * 64))
  447. {
  448. $span = 'several decades';
  449. }
  450. else
  451. {
  452. $span = 'a long time';
  453. }
  454. if ($timestamp <= $local_timestamp)
  455. {
  456. // This is in the past
  457. return $span.' ago';
  458. }
  459. else
  460. {
  461. // This in the future
  462. return 'in '.$span;
  463. }
  464. }
  465. /**
  466. * Converts a UNIX timestamp to DOS format. There are very few cases where
  467. * this is needed, but some binary formats use it (eg: zip files.)
  468. * Converting the other direction is done using {@link Date::dos2unix}.
  469. *
  470. * $dos = Date::unix2dos($unix);
  471. *
  472. * @param integer $timestamp UNIX timestamp
  473. * @return integer
  474. */
  475. public static function unix2dos($timestamp = FALSE)
  476. {
  477. $timestamp = ($timestamp === FALSE) ? getdate() : getdate($timestamp);
  478. if ($timestamp['year'] < 1980)
  479. {
  480. return (1 << 21 | 1 << 16);
  481. }
  482. $timestamp['year'] -= 1980;
  483. // What voodoo is this? I have no idea... Geert can explain it though,
  484. // and that's good enough for me.
  485. return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 |
  486. $timestamp['mday'] << 16 | $timestamp['hours'] << 11 |
  487. $timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1);
  488. }
  489. /**
  490. * Converts a DOS timestamp to UNIX format.There are very few cases where
  491. * this is needed, but some binary formats use it (eg: zip files.)
  492. * Converting the other direction is done using {@link Date::unix2dos}.
  493. *
  494. * $unix = Date::dos2unix($dos);
  495. *
  496. * @param integer $timestamp DOS timestamp
  497. * @return integer
  498. */
  499. public static function dos2unix($timestamp = FALSE)
  500. {
  501. $sec = 2 * ($timestamp & 0x1f);
  502. $min = ($timestamp >> 5) & 0x3f;
  503. $hrs = ($timestamp >> 11) & 0x1f;
  504. $day = ($timestamp >> 16) & 0x1f;
  505. $mon = ($timestamp >> 21) & 0x0f;
  506. $year = ($timestamp >> 25) & 0x7f;
  507. return mktime($hrs, $min, $sec, $mon, $day, $year + 1980);
  508. }
  509. /**
  510. * Returns a date/time string with the specified timestamp format
  511. *
  512. * $time = Date::formatted_time('5 minutes ago');
  513. *
  514. * @link http://www.php.net/manual/datetime.construct
  515. * @param string $datetime_str datetime string
  516. * @param string $timestamp_format timestamp format
  517. * @param string $timezone timezone identifier
  518. * @return string
  519. */
  520. public static function formatted_time($datetime_str = 'now', $timestamp_format = NULL, $timezone = NULL)
  521. {
  522. $timestamp_format = ($timestamp_format == NULL) ? Date::$timestamp_format : $timestamp_format;
  523. $timezone = ($timezone === NULL) ? Date::$timezone : $timezone;
  524. $tz = new DateTimeZone($timezone ? $timezone : date_default_timezone_get());
  525. $time = new DateTime($datetime_str, $tz);
  526. // Convert the time back to the expected timezone if required (in case the datetime_str provided a timezone,
  527. // offset or unix timestamp. This also ensures that the timezone reported by the object is correct on HHVM
  528. // (see https://github.com/facebook/hhvm/issues/2302).
  529. $time->setTimeZone($tz);
  530. return $time->format($timestamp_format);
  531. }
  532. }