Base for a static organization website

CakeTime.php 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  1. <?php
  2. /**
  3. * CakeTime utility class file.
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Utility
  15. * @since CakePHP(tm) v 0.10.0.1076
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. App::uses('Multibyte', 'I18n');
  19. /**
  20. * Time Helper class for easy use of time data.
  21. *
  22. * Manipulation of time data.
  23. *
  24. * @package Cake.Utility
  25. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html
  26. */
  27. class CakeTime {
  28. /**
  29. * The format to use when formatting a time using `CakeTime::nice()`
  30. *
  31. * The format should use the locale strings as defined in the PHP docs under
  32. * `strftime` (http://php.net/manual/en/function.strftime.php)
  33. *
  34. * @var string
  35. * @see CakeTime::format()
  36. */
  37. public static $niceFormat = '%a, %b %eS %Y, %H:%M';
  38. /**
  39. * The format to use when formatting a time using `CakeTime::timeAgoInWords()`
  40. * and the difference is more than `CakeTime::$wordEnd`
  41. *
  42. * @var string
  43. * @see CakeTime::timeAgoInWords()
  44. */
  45. public static $wordFormat = 'j/n/y';
  46. /**
  47. * The format to use when formatting a time using `CakeTime::niceShort()`
  48. * and the difference is between 3 and 7 days
  49. *
  50. * @var string
  51. * @see CakeTime::niceShort()
  52. */
  53. public static $niceShortFormat = '%B %d, %H:%M';
  54. /**
  55. * The format to use when formatting a time using `CakeTime::timeAgoInWords()`
  56. * and the difference is less than `CakeTime::$wordEnd`
  57. *
  58. * @var array
  59. * @see CakeTime::timeAgoInWords()
  60. */
  61. public static $wordAccuracy = array(
  62. 'year' => 'day',
  63. 'month' => 'day',
  64. 'week' => 'day',
  65. 'day' => 'hour',
  66. 'hour' => 'minute',
  67. 'minute' => 'minute',
  68. 'second' => 'second',
  69. );
  70. /**
  71. * The end of relative time telling
  72. *
  73. * @var string
  74. * @see CakeTime::timeAgoInWords()
  75. */
  76. public static $wordEnd = '+1 month';
  77. /**
  78. * Temporary variable containing the timestamp value, used internally in convertSpecifiers()
  79. *
  80. * @var int
  81. */
  82. protected static $_time = null;
  83. /**
  84. * Magic set method for backwards compatibility.
  85. * Used by TimeHelper to modify static variables in CakeTime
  86. *
  87. * @param string $name Variable name
  88. * @param mixes $value Variable value
  89. * @return void
  90. */
  91. public function __set($name, $value) {
  92. switch ($name) {
  93. case 'niceFormat':
  94. static::${$name} = $value;
  95. break;
  96. }
  97. }
  98. /**
  99. * Magic set method for backwards compatibility.
  100. * Used by TimeHelper to get static variables in CakeTime
  101. *
  102. * @param string $name Variable name
  103. * @return mixed
  104. */
  105. public function __get($name) {
  106. switch ($name) {
  107. case 'niceFormat':
  108. return static::${$name};
  109. default:
  110. return null;
  111. }
  112. }
  113. /**
  114. * Converts a string representing the format for the function strftime and returns a
  115. * Windows safe and i18n aware format.
  116. *
  117. * @param string $format Format with specifiers for strftime function.
  118. * Accepts the special specifier %S which mimics the modifier S for date()
  119. * @param string $time UNIX timestamp
  120. * @return string Windows safe and date() function compatible format for strftime
  121. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::convertSpecifiers
  122. */
  123. public static function convertSpecifiers($format, $time = null) {
  124. if (!$time) {
  125. $time = time();
  126. }
  127. static::$_time = $time;
  128. return preg_replace_callback('/\%(\w+)/', array('CakeTime', '_translateSpecifier'), $format);
  129. }
  130. /**
  131. * Auxiliary function to translate a matched specifier element from a regular expression into
  132. * a Windows safe and i18n aware specifier
  133. *
  134. * @param array $specifier match from regular expression
  135. * @return string converted element
  136. */
  137. protected static function _translateSpecifier($specifier) {
  138. switch ($specifier[1]) {
  139. case 'a':
  140. $abday = __dc('cake', 'abday', 5);
  141. if (is_array($abday)) {
  142. return $abday[date('w', static::$_time)];
  143. }
  144. break;
  145. case 'A':
  146. $day = __dc('cake', 'day', 5);
  147. if (is_array($day)) {
  148. return $day[date('w', static::$_time)];
  149. }
  150. break;
  151. case 'c':
  152. $format = __dc('cake', 'd_t_fmt', 5);
  153. if ($format !== 'd_t_fmt') {
  154. return static::convertSpecifiers($format, static::$_time);
  155. }
  156. break;
  157. case 'C':
  158. return sprintf("%02d", date('Y', static::$_time) / 100);
  159. case 'D':
  160. return '%m/%d/%y';
  161. case 'e':
  162. if (DS === '/') {
  163. return '%e';
  164. }
  165. $day = date('j', static::$_time);
  166. if ($day < 10) {
  167. $day = ' ' . $day;
  168. }
  169. return $day;
  170. case 'eS' :
  171. return date('jS', static::$_time);
  172. case 'b':
  173. case 'h':
  174. $months = __dc('cake', 'abmon', 5);
  175. if (is_array($months)) {
  176. return $months[date('n', static::$_time) - 1];
  177. }
  178. return '%b';
  179. case 'B':
  180. $months = __dc('cake', 'mon', 5);
  181. if (is_array($months)) {
  182. return $months[date('n', static::$_time) - 1];
  183. }
  184. break;
  185. case 'n':
  186. return "\n";
  187. case 'p':
  188. case 'P':
  189. $default = array('am' => 0, 'pm' => 1);
  190. $meridiem = $default[date('a', static::$_time)];
  191. $format = __dc('cake', 'am_pm', 5);
  192. if (is_array($format)) {
  193. $meridiem = $format[$meridiem];
  194. return ($specifier[1] === 'P') ? strtolower($meridiem) : strtoupper($meridiem);
  195. }
  196. break;
  197. case 'r':
  198. $complete = __dc('cake', 't_fmt_ampm', 5);
  199. if ($complete !== 't_fmt_ampm') {
  200. return str_replace('%p', static::_translateSpecifier(array('%p', 'p')), $complete);
  201. }
  202. break;
  203. case 'R':
  204. return date('H:i', static::$_time);
  205. case 't':
  206. return "\t";
  207. case 'T':
  208. return '%H:%M:%S';
  209. case 'u':
  210. return ($weekDay = date('w', static::$_time)) ? $weekDay : 7;
  211. case 'x':
  212. $format = __dc('cake', 'd_fmt', 5);
  213. if ($format !== 'd_fmt') {
  214. return static::convertSpecifiers($format, static::$_time);
  215. }
  216. break;
  217. case 'X':
  218. $format = __dc('cake', 't_fmt', 5);
  219. if ($format !== 't_fmt') {
  220. return static::convertSpecifiers($format, static::$_time);
  221. }
  222. break;
  223. }
  224. return $specifier[0];
  225. }
  226. /**
  227. * Converts given time (in server's time zone) to user's local time, given his/her timezone.
  228. *
  229. * @param string $serverTime UNIX timestamp
  230. * @param string|DateTimeZone $timezone User's timezone string or DateTimeZone object
  231. * @return int UNIX timestamp
  232. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::convert
  233. */
  234. public static function convert($serverTime, $timezone) {
  235. static $serverTimezone = null;
  236. if ($serverTimezone === null || (date_default_timezone_get() !== $serverTimezone->getName())) {
  237. $serverTimezone = new DateTimeZone(date_default_timezone_get());
  238. }
  239. $serverOffset = $serverTimezone->getOffset(new DateTime('@' . $serverTime));
  240. $gmtTime = $serverTime - $serverOffset;
  241. if (is_numeric($timezone)) {
  242. $userOffset = $timezone * (60 * 60);
  243. } else {
  244. $timezone = static::timezone($timezone);
  245. $userOffset = $timezone->getOffset(new DateTime('@' . $gmtTime));
  246. }
  247. $userTime = $gmtTime + $userOffset;
  248. return (int)$userTime;
  249. }
  250. /**
  251. * Returns a timezone object from a string or the user's timezone object
  252. *
  253. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  254. * If null it tries to get timezone from 'Config.timezone' config var
  255. * @return DateTimeZone Timezone object
  256. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::timezone
  257. */
  258. public static function timezone($timezone = null) {
  259. static $tz = null;
  260. if (is_object($timezone)) {
  261. if ($tz === null || $tz->getName() !== $timezone->getName()) {
  262. $tz = $timezone;
  263. }
  264. } else {
  265. if ($timezone === null) {
  266. $timezone = Configure::read('Config.timezone');
  267. if ($timezone === null) {
  268. $timezone = date_default_timezone_get();
  269. }
  270. }
  271. if ($tz === null || $tz->getName() !== $timezone) {
  272. $tz = new DateTimeZone($timezone);
  273. }
  274. }
  275. return $tz;
  276. }
  277. /**
  278. * Returns server's offset from GMT in seconds.
  279. *
  280. * @return int Offset
  281. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::serverOffset
  282. */
  283. public static function serverOffset() {
  284. return date('Z', time());
  285. }
  286. /**
  287. * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
  288. *
  289. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  290. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  291. * @return string Parsed timestamp
  292. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::fromString
  293. */
  294. public static function fromString($dateString, $timezone = null) {
  295. if (empty($dateString)) {
  296. return false;
  297. }
  298. $containsDummyDate = (is_string($dateString) && substr($dateString, 0, 10) === '0000-00-00');
  299. if ($containsDummyDate) {
  300. return false;
  301. }
  302. if (is_int($dateString) || is_numeric($dateString)) {
  303. $date = (int)$dateString;
  304. } elseif ($dateString instanceof DateTime &&
  305. $dateString->getTimezone()->getName() != date_default_timezone_get()
  306. ) {
  307. $clone = clone $dateString;
  308. $clone->setTimezone(new DateTimeZone(date_default_timezone_get()));
  309. $date = (int)$clone->format('U') + $clone->getOffset();
  310. } elseif ($dateString instanceof DateTime) {
  311. $date = (int)$dateString->format('U');
  312. } else {
  313. $date = strtotime($dateString);
  314. }
  315. if ($date === -1 || empty($date)) {
  316. return false;
  317. }
  318. if ($timezone === null) {
  319. $timezone = Configure::read('Config.timezone');
  320. }
  321. if ($timezone !== null) {
  322. return static::convert($date, $timezone);
  323. }
  324. return $date;
  325. }
  326. /**
  327. * Returns a nicely formatted date string for given Datetime string.
  328. *
  329. * See http://php.net/manual/en/function.strftime.php for information on formatting
  330. * using locale strings.
  331. *
  332. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  333. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  334. * @param string $format The format to use. If null, `CakeTime::$niceFormat` is used
  335. * @return string Formatted date string
  336. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::nice
  337. */
  338. public static function nice($dateString = null, $timezone = null, $format = null) {
  339. if (!$dateString) {
  340. $dateString = time();
  341. }
  342. $date = static::fromString($dateString, $timezone);
  343. if (!$format) {
  344. $format = static::$niceFormat;
  345. }
  346. return static::_strftime(static::convertSpecifiers($format, $date), $date);
  347. }
  348. /**
  349. * Returns a formatted descriptive date string for given datetime string.
  350. *
  351. * If the given date is today, the returned string could be "Today, 16:54".
  352. * If the given date is tomorrow, the returned string could be "Tomorrow, 16:54".
  353. * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
  354. * If the given date is within next or last week, the returned string could be "On Thursday, 16:54".
  355. * If $dateString's year is the current year, the returned string does not
  356. * include mention of the year.
  357. *
  358. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  359. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  360. * @return string Described, relative date string
  361. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::niceShort
  362. */
  363. public static function niceShort($dateString = null, $timezone = null) {
  364. if (!$dateString) {
  365. $dateString = time();
  366. }
  367. $date = static::fromString($dateString, $timezone);
  368. if (static::isToday($dateString, $timezone)) {
  369. return __d('cake', 'Today, %s', static::_strftime("%H:%M", $date));
  370. }
  371. if (static::wasYesterday($dateString, $timezone)) {
  372. return __d('cake', 'Yesterday, %s', static::_strftime("%H:%M", $date));
  373. }
  374. if (static::isTomorrow($dateString, $timezone)) {
  375. return __d('cake', 'Tomorrow, %s', static::_strftime("%H:%M", $date));
  376. }
  377. $d = static::_strftime("%w", $date);
  378. $day = array(
  379. __d('cake', 'Sunday'),
  380. __d('cake', 'Monday'),
  381. __d('cake', 'Tuesday'),
  382. __d('cake', 'Wednesday'),
  383. __d('cake', 'Thursday'),
  384. __d('cake', 'Friday'),
  385. __d('cake', 'Saturday')
  386. );
  387. if (static::wasWithinLast('7 days', $dateString, $timezone)) {
  388. return sprintf('%s %s', $day[$d], static::_strftime(static::$niceShortFormat, $date));
  389. }
  390. if (static::isWithinNext('7 days', $dateString, $timezone)) {
  391. return __d('cake', 'On %s %s', $day[$d], static::_strftime(static::$niceShortFormat, $date));
  392. }
  393. $y = '';
  394. if (!static::isThisYear($date)) {
  395. $y = ' %Y';
  396. }
  397. return static::_strftime(static::convertSpecifiers("%b %eS{$y}, %H:%M", $date), $date);
  398. }
  399. /**
  400. * Returns a partial SQL string to search for all records between two dates.
  401. *
  402. * @param int|string|DateTime $begin UNIX timestamp, strtotime() valid string or DateTime object
  403. * @param int|string|DateTime $end UNIX timestamp, strtotime() valid string or DateTime object
  404. * @param string $fieldName Name of database field to compare with
  405. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  406. * @return string Partial SQL string.
  407. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::daysAsSql
  408. */
  409. public static function daysAsSql($begin, $end, $fieldName, $timezone = null) {
  410. $begin = static::fromString($begin, $timezone);
  411. $end = static::fromString($end, $timezone);
  412. $begin = date('Y-m-d', $begin) . ' 00:00:00';
  413. $end = date('Y-m-d', $end) . ' 23:59:59';
  414. return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
  415. }
  416. /**
  417. * Returns a partial SQL string to search for all records between two times
  418. * occurring on the same day.
  419. *
  420. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  421. * @param string $fieldName Name of database field to compare with
  422. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  423. * @return string Partial SQL string.
  424. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::dayAsSql
  425. */
  426. public static function dayAsSql($dateString, $fieldName, $timezone = null) {
  427. return static::daysAsSql($dateString, $dateString, $fieldName, $timezone);
  428. }
  429. /**
  430. * Returns true if given datetime string is today.
  431. *
  432. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  433. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  434. * @return bool True if datetime string is today
  435. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isToday
  436. */
  437. public static function isToday($dateString, $timezone = null) {
  438. $timestamp = static::fromString($dateString, $timezone);
  439. $now = static::fromString('now', $timezone);
  440. return date('Y-m-d', $timestamp) === date('Y-m-d', $now);
  441. }
  442. /**
  443. * Returns true if given datetime string is in the future.
  444. *
  445. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  446. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  447. * @return bool True if datetime string is in the future
  448. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isFuture
  449. */
  450. public static function isFuture($dateString, $timezone = null) {
  451. $timestamp = static::fromString($dateString, $timezone);
  452. return $timestamp > time();
  453. }
  454. /**
  455. * Returns true if given datetime string is in the past.
  456. *
  457. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  458. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  459. * @return bool True if datetime string is in the past
  460. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isPast
  461. */
  462. public static function isPast($dateString, $timezone = null) {
  463. $timestamp = static::fromString($dateString, $timezone);
  464. return $timestamp < time();
  465. }
  466. /**
  467. * Returns true if given datetime string is within this week.
  468. *
  469. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  470. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  471. * @return bool True if datetime string is within current week
  472. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisWeek
  473. */
  474. public static function isThisWeek($dateString, $timezone = null) {
  475. $timestamp = static::fromString($dateString, $timezone);
  476. $now = static::fromString('now', $timezone);
  477. return date('W o', $timestamp) === date('W o', $now);
  478. }
  479. /**
  480. * Returns true if given datetime string is within this month
  481. *
  482. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  483. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  484. * @return bool True if datetime string is within current month
  485. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisMonth
  486. */
  487. public static function isThisMonth($dateString, $timezone = null) {
  488. $timestamp = static::fromString($dateString, $timezone);
  489. $now = static::fromString('now', $timezone);
  490. return date('m Y', $timestamp) === date('m Y', $now);
  491. }
  492. /**
  493. * Returns true if given datetime string is within current year.
  494. *
  495. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  496. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  497. * @return bool True if datetime string is within current year
  498. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisYear
  499. */
  500. public static function isThisYear($dateString, $timezone = null) {
  501. $timestamp = static::fromString($dateString, $timezone);
  502. $now = static::fromString('now', $timezone);
  503. return date('Y', $timestamp) === date('Y', $now);
  504. }
  505. /**
  506. * Returns true if given datetime string was yesterday.
  507. *
  508. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  509. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  510. * @return bool True if datetime string was yesterday
  511. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::wasYesterday
  512. */
  513. public static function wasYesterday($dateString, $timezone = null) {
  514. $timestamp = static::fromString($dateString, $timezone);
  515. $yesterday = static::fromString('yesterday', $timezone);
  516. return date('Y-m-d', $timestamp) === date('Y-m-d', $yesterday);
  517. }
  518. /**
  519. * Returns true if given datetime string is tomorrow.
  520. *
  521. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  522. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  523. * @return bool True if datetime string was yesterday
  524. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isTomorrow
  525. */
  526. public static function isTomorrow($dateString, $timezone = null) {
  527. $timestamp = static::fromString($dateString, $timezone);
  528. $tomorrow = static::fromString('tomorrow', $timezone);
  529. return date('Y-m-d', $timestamp) === date('Y-m-d', $tomorrow);
  530. }
  531. /**
  532. * Returns the quarter
  533. *
  534. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  535. * @param bool $range if true returns a range in Y-m-d format
  536. * @return int|array 1, 2, 3, or 4 quarter of year or array if $range true
  537. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toQuarter
  538. */
  539. public static function toQuarter($dateString, $range = false) {
  540. $time = static::fromString($dateString);
  541. $date = (int)ceil(date('m', $time) / 3);
  542. if ($range === false) {
  543. return $date;
  544. }
  545. $year = date('Y', $time);
  546. switch ($date) {
  547. case 1:
  548. return array($year . '-01-01', $year . '-03-31');
  549. case 2:
  550. return array($year . '-04-01', $year . '-06-30');
  551. case 3:
  552. return array($year . '-07-01', $year . '-09-30');
  553. case 4:
  554. return array($year . '-10-01', $year . '-12-31');
  555. }
  556. }
  557. /**
  558. * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
  559. *
  560. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  561. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  562. * @return int Unix timestamp
  563. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toUnix
  564. */
  565. public static function toUnix($dateString, $timezone = null) {
  566. return static::fromString($dateString, $timezone);
  567. }
  568. /**
  569. * Returns a formatted date in server's timezone.
  570. *
  571. * If a DateTime object is given or the dateString has a timezone
  572. * segment, the timezone parameter will be ignored.
  573. *
  574. * If no timezone parameter is given and no DateTime object, the passed $dateString will be
  575. * considered to be in the UTC timezone.
  576. *
  577. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  578. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  579. * @param string $format date format string
  580. * @return mixed Formatted date
  581. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toServer
  582. */
  583. public static function toServer($dateString, $timezone = null, $format = 'Y-m-d H:i:s') {
  584. if ($timezone === null) {
  585. $timezone = new DateTimeZone('UTC');
  586. } elseif (is_string($timezone)) {
  587. $timezone = new DateTimeZone($timezone);
  588. } elseif (!($timezone instanceof DateTimeZone)) {
  589. return false;
  590. }
  591. if ($dateString instanceof DateTime) {
  592. $date = $dateString;
  593. } elseif (is_int($dateString) || is_numeric($dateString)) {
  594. $dateString = (int)$dateString;
  595. $date = new DateTime('@' . $dateString);
  596. $date->setTimezone($timezone);
  597. } else {
  598. $date = new DateTime($dateString, $timezone);
  599. }
  600. $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
  601. return $date->format($format);
  602. }
  603. /**
  604. * Returns a date formatted for Atom RSS feeds.
  605. *
  606. * @param string $dateString Datetime string or Unix timestamp
  607. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  608. * @return string Formatted date string
  609. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toAtom
  610. */
  611. public static function toAtom($dateString, $timezone = null) {
  612. return date('Y-m-d\TH:i:s\Z', static::fromString($dateString, $timezone));
  613. }
  614. /**
  615. * Formats date for RSS feeds
  616. *
  617. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  618. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  619. * @return string Formatted date string
  620. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toRSS
  621. */
  622. public static function toRSS($dateString, $timezone = null) {
  623. $date = static::fromString($dateString, $timezone);
  624. if ($timezone === null) {
  625. return date("r", $date);
  626. }
  627. $userOffset = $timezone;
  628. if (!is_numeric($timezone)) {
  629. if (!is_object($timezone)) {
  630. $timezone = new DateTimeZone($timezone);
  631. }
  632. $currentDate = new DateTime('@' . $date);
  633. $currentDate->setTimezone($timezone);
  634. $userOffset = $timezone->getOffset($currentDate) / 60 / 60;
  635. }
  636. $timezone = '+0000';
  637. if ($userOffset != 0) {
  638. $hours = (int)floor(abs($userOffset));
  639. $minutes = (int)(fmod(abs($userOffset), $hours) * 60);
  640. $timezone = ($userOffset < 0 ? '-' : '+') . str_pad($hours, 2, '0', STR_PAD_LEFT) . str_pad($minutes, 2, '0', STR_PAD_LEFT);
  641. }
  642. return date('D, d M Y H:i:s', $date) . ' ' . $timezone;
  643. }
  644. /**
  645. * Returns either a relative or a formatted absolute date depending
  646. * on the difference between the current time and given datetime.
  647. * $datetime should be in a *strtotime* - parsable format, like MySQL's datetime datatype.
  648. *
  649. * ### Options:
  650. *
  651. * - `format` => a fall back format if the relative time is longer than the duration specified by end
  652. * - `accuracy` => Specifies how accurate the date should be described (array)
  653. * - year => The format if years > 0 (default "day")
  654. * - month => The format if months > 0 (default "day")
  655. * - week => The format if weeks > 0 (default "day")
  656. * - day => The format if weeks > 0 (default "hour")
  657. * - hour => The format if hours > 0 (default "minute")
  658. * - minute => The format if minutes > 0 (default "minute")
  659. * - second => The format if seconds > 0 (default "second")
  660. * - `end` => The end of relative time telling
  661. * - `relativeString` => The printf compatible string when outputting past relative time
  662. * - `relativeStringFuture` => The printf compatible string when outputting future relative time
  663. * - `absoluteString` => The printf compatible string when outputting absolute time
  664. * - `userOffset` => Users offset from GMT (in hours) *Deprecated* use timezone instead.
  665. * - `timezone` => The user timezone the timestamp should be formatted in.
  666. *
  667. * Relative dates look something like this:
  668. *
  669. * - 3 weeks, 4 days ago
  670. * - 15 seconds ago
  671. *
  672. * Default date formatting is d/m/yy e.g: on 18/2/09
  673. *
  674. * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
  675. * like 'Posted ' before the function output.
  676. *
  677. * NOTE: If the difference is one week or more, the lowest level of accuracy is day
  678. *
  679. * @param int|string|DateTime $dateTime Datetime UNIX timestamp, strtotime() valid string or DateTime object
  680. * @param array $options Default format if timestamp is used in $dateString
  681. * @return string Relative time string.
  682. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::timeAgoInWords
  683. */
  684. public static function timeAgoInWords($dateTime, $options = array()) {
  685. $timezone = null;
  686. $accuracies = static::$wordAccuracy;
  687. $format = static::$wordFormat;
  688. $relativeEnd = static::$wordEnd;
  689. $relativeStringPast = __d('cake', '%s ago');
  690. $relativeStringFuture = __d('cake', 'in %s');
  691. $absoluteString = __d('cake', 'on %s');
  692. if (is_string($options)) {
  693. $format = $options;
  694. } elseif (!empty($options)) {
  695. if (isset($options['timezone'])) {
  696. $timezone = $options['timezone'];
  697. } elseif (isset($options['userOffset'])) {
  698. $timezone = $options['userOffset'];
  699. }
  700. if (isset($options['accuracy'])) {
  701. if (is_array($options['accuracy'])) {
  702. $accuracies = array_merge($accuracies, $options['accuracy']);
  703. } else {
  704. foreach ($accuracies as $key => $level) {
  705. $accuracies[$key] = $options['accuracy'];
  706. }
  707. }
  708. }
  709. if (isset($options['format'])) {
  710. $format = $options['format'];
  711. }
  712. if (isset($options['end'])) {
  713. $relativeEnd = $options['end'];
  714. }
  715. if (isset($options['relativeString'])) {
  716. $relativeStringPast = $options['relativeString'];
  717. unset($options['relativeString']);
  718. }
  719. if (isset($options['relativeStringFuture'])) {
  720. $relativeStringFuture = $options['relativeStringFuture'];
  721. unset($options['relativeStringFuture']);
  722. }
  723. if (isset($options['absoluteString'])) {
  724. $absoluteString = $options['absoluteString'];
  725. unset($options['absoluteString']);
  726. }
  727. unset($options['end'], $options['format']);
  728. }
  729. $now = static::fromString(time(), $timezone);
  730. $inSeconds = static::fromString($dateTime, $timezone);
  731. $isFuture = ($inSeconds > $now);
  732. if ($isFuture) {
  733. $startTime = $now;
  734. $endTime = $inSeconds;
  735. } else {
  736. $startTime = $inSeconds;
  737. $endTime = $now;
  738. }
  739. $diff = $endTime - $startTime;
  740. if ($diff === 0) {
  741. return __d('cake', 'just now', 'just now');
  742. }
  743. $isAbsoluteDate = $diff > abs($now - static::fromString($relativeEnd));
  744. if ($isAbsoluteDate) {
  745. if (strpos($format, '%') === false) {
  746. $date = date($format, $inSeconds);
  747. } else {
  748. $date = static::_strftime($format, $inSeconds);
  749. }
  750. return sprintf($absoluteString, $date);
  751. }
  752. $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
  753. // If more than a week, then take into account the length of months
  754. if ($diff >= 604800) {
  755. list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $endTime));
  756. list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $startTime));
  757. $years = $future['Y'] - $past['Y'];
  758. $months = $future['m'] + ((12 * $years) - $past['m']);
  759. if ($months >= 12) {
  760. $years = floor($months / 12);
  761. $months = $months - ($years * 12);
  762. }
  763. if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] === 1) {
  764. $years--;
  765. }
  766. if ($future['d'] >= $past['d']) {
  767. $days = $future['d'] - $past['d'];
  768. } else {
  769. $daysInPastMonth = date('t', $startTime);
  770. $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
  771. if ($isFuture) {
  772. $days = ($daysInFutureMonth - $past['d']) + $future['d'];
  773. } else {
  774. $days = ($daysInPastMonth - $past['d']) + $future['d'];
  775. }
  776. if ($future['m'] != $past['m']) {
  777. $months--;
  778. }
  779. }
  780. if (!$months && $years >= 1 && $diff < ($years * 31536000)) {
  781. $months = 11;
  782. $years--;
  783. }
  784. if ($months >= 12) {
  785. $years = $years + 1;
  786. $months = $months - 12;
  787. }
  788. if ($days >= 7) {
  789. $weeks = floor($days / 7);
  790. $days = $days - ($weeks * 7);
  791. }
  792. } else {
  793. $days = floor($diff / 86400);
  794. $diff = $diff - ($days * 86400);
  795. $hours = floor($diff / 3600);
  796. $diff = $diff - ($hours * 3600);
  797. $minutes = floor($diff / 60);
  798. $diff = $diff - ($minutes * 60);
  799. $seconds = $diff;
  800. }
  801. $accuracy = $accuracies['second'];
  802. if ($years > 0) {
  803. $accuracy = $accuracies['year'];
  804. } elseif (abs($months) > 0) {
  805. $accuracy = $accuracies['month'];
  806. } elseif (abs($weeks) > 0) {
  807. $accuracy = $accuracies['week'];
  808. } elseif (abs($days) > 0) {
  809. $accuracy = $accuracies['day'];
  810. } elseif (abs($hours) > 0) {
  811. $accuracy = $accuracies['hour'];
  812. } elseif (abs($minutes) > 0) {
  813. $accuracy = $accuracies['minute'];
  814. }
  815. $accuracyNum = str_replace(array('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), array(1, 2, 3, 4, 5, 6, 7), $accuracy);
  816. $relativeDate = array();
  817. if ($accuracyNum >= 1 && $years > 0) {
  818. $relativeDate[] = __dn('cake', '%d year', '%d years', $years, $years);
  819. }
  820. if ($accuracyNum >= 2 && $months > 0) {
  821. $relativeDate[] = __dn('cake', '%d month', '%d months', $months, $months);
  822. }
  823. if ($accuracyNum >= 3 && $weeks > 0) {
  824. $relativeDate[] = __dn('cake', '%d week', '%d weeks', $weeks, $weeks);
  825. }
  826. if ($accuracyNum >= 4 && $days > 0) {
  827. $relativeDate[] = __dn('cake', '%d day', '%d days', $days, $days);
  828. }
  829. if ($accuracyNum >= 5 && $hours > 0) {
  830. $relativeDate[] = __dn('cake', '%d hour', '%d hours', $hours, $hours);
  831. }
  832. if ($accuracyNum >= 6 && $minutes > 0) {
  833. $relativeDate[] = __dn('cake', '%d minute', '%d minutes', $minutes, $minutes);
  834. }
  835. if ($accuracyNum >= 7 && $seconds > 0) {
  836. $relativeDate[] = __dn('cake', '%d second', '%d seconds', $seconds, $seconds);
  837. }
  838. $relativeDate = implode(', ', $relativeDate);
  839. if ($relativeDate) {
  840. $relativeString = ($isFuture) ? $relativeStringFuture : $relativeStringPast;
  841. return sprintf($relativeString, $relativeDate);
  842. }
  843. if ($isFuture) {
  844. $strings = array(
  845. 'second' => __d('cake', 'in about a second'),
  846. 'minute' => __d('cake', 'in about a minute'),
  847. 'hour' => __d('cake', 'in about an hour'),
  848. 'day' => __d('cake', 'in about a day'),
  849. 'week' => __d('cake', 'in about a week'),
  850. 'year' => __d('cake', 'in about a year')
  851. );
  852. } else {
  853. $strings = array(
  854. 'second' => __d('cake', 'about a second ago'),
  855. 'minute' => __d('cake', 'about a minute ago'),
  856. 'hour' => __d('cake', 'about an hour ago'),
  857. 'day' => __d('cake', 'about a day ago'),
  858. 'week' => __d('cake', 'about a week ago'),
  859. 'year' => __d('cake', 'about a year ago')
  860. );
  861. }
  862. return $strings[$accuracy];
  863. }
  864. /**
  865. * Returns true if specified datetime was within the interval specified, else false.
  866. *
  867. * @param string|int $timeInterval the numeric value with space then time type.
  868. * Example of valid types: 6 hours, 2 days, 1 minute.
  869. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  870. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  871. * @return bool
  872. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::wasWithinLast
  873. */
  874. public static function wasWithinLast($timeInterval, $dateString, $timezone = null) {
  875. $tmp = str_replace(' ', '', $timeInterval);
  876. if (is_numeric($tmp)) {
  877. $timeInterval = $tmp . ' ' . __d('cake', 'days');
  878. }
  879. $date = static::fromString($dateString, $timezone);
  880. $interval = static::fromString('-' . $timeInterval);
  881. $now = static::fromString('now', $timezone);
  882. return $date >= $interval && $date <= $now;
  883. }
  884. /**
  885. * Returns true if specified datetime is within the interval specified, else false.
  886. *
  887. * @param string|int $timeInterval the numeric value with space then time type.
  888. * Example of valid types: 6 hours, 2 days, 1 minute.
  889. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  890. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  891. * @return bool
  892. */
  893. public static function isWithinNext($timeInterval, $dateString, $timezone = null) {
  894. $tmp = str_replace(' ', '', $timeInterval);
  895. if (is_numeric($tmp)) {
  896. $timeInterval = $tmp . ' ' . __d('cake', 'days');
  897. }
  898. $date = static::fromString($dateString, $timezone);
  899. $interval = static::fromString('+' . $timeInterval);
  900. $now = static::fromString('now', $timezone);
  901. return $date <= $interval && $date >= $now;
  902. }
  903. /**
  904. * Returns gmt as a UNIX timestamp.
  905. *
  906. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  907. * @return int UNIX timestamp
  908. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::gmt
  909. */
  910. public static function gmt($dateString = null) {
  911. $time = time();
  912. if ($dateString) {
  913. $time = static::fromString($dateString);
  914. }
  915. return gmmktime(
  916. (int)date('G', $time),
  917. (int)date('i', $time),
  918. (int)date('s', $time),
  919. (int)date('n', $time),
  920. (int)date('j', $time),
  921. (int)date('Y', $time)
  922. );
  923. }
  924. /**
  925. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  926. * This function also accepts a time string and a format string as first and second parameters.
  927. * In that case this function behaves as a wrapper for TimeHelper::i18nFormat()
  928. *
  929. * ## Examples
  930. *
  931. * Create localized & formatted time:
  932. *
  933. * ```
  934. * CakeTime::format('2012-02-15', '%m-%d-%Y'); // returns 02-15-2012
  935. * CakeTime::format('2012-02-15 23:01:01', '%c'); // returns preferred date and time based on configured locale
  936. * CakeTime::format('0000-00-00', '%d-%m-%Y', 'N/A'); // return N/A becuase an invalid date was passed
  937. * CakeTime::format('2012-02-15 23:01:01', '%c', 'N/A', 'America/New_York'); // converts passed date to timezone
  938. * ```
  939. *
  940. * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object (or a date format string)
  941. * @param int|string|DateTime $format date format string (or UNIX timestamp, strtotime() valid string or DateTime object)
  942. * @param bool|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
  943. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  944. * @return string Formatted date string
  945. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::format
  946. * @see CakeTime::i18nFormat()
  947. */
  948. public static function format($date, $format = null, $default = false, $timezone = null) {
  949. //Backwards compatible params re-order test
  950. $time = static::fromString($format, $timezone);
  951. if ($time === false) {
  952. return static::i18nFormat($date, $format, $default, $timezone);
  953. }
  954. return date($date, $time);
  955. }
  956. /**
  957. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  958. * It takes into account the default date format for the current language if a LC_TIME file is used.
  959. *
  960. * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object
  961. * @param string $format strftime format string.
  962. * @param bool|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
  963. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  964. * @return string Formatted and translated date string
  965. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::i18nFormat
  966. */
  967. public static function i18nFormat($date, $format = null, $default = false, $timezone = null) {
  968. $date = static::fromString($date, $timezone);
  969. if ($date === false && $default !== false) {
  970. return $default;
  971. }
  972. if ($date === false) {
  973. return '';
  974. }
  975. if (empty($format)) {
  976. $format = '%x';
  977. }
  978. return static::_strftime(static::convertSpecifiers($format, $date), $date);
  979. }
  980. /**
  981. * Get list of timezone identifiers
  982. *
  983. * @param int|string $filter A regex to filter identifier
  984. * Or one of DateTimeZone class constants (PHP 5.3 and above)
  985. * @param string $country A two-letter ISO 3166-1 compatible country code.
  986. * This option is only used when $filter is set to DateTimeZone::PER_COUNTRY (available only in PHP 5.3 and above)
  987. * @param bool $group If true (default value) groups the identifiers list by primary region
  988. * @return array List of timezone identifiers
  989. * @since 2.2
  990. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::listTimezones
  991. */
  992. public static function listTimezones($filter = null, $country = null, $group = true) {
  993. $regex = null;
  994. if (is_string($filter)) {
  995. $regex = $filter;
  996. $filter = null;
  997. }
  998. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  999. if ($regex === null) {
  1000. $regex = '#^((Africa|America|Antartica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC)#';
  1001. }
  1002. $identifiers = DateTimeZone::listIdentifiers();
  1003. } else {
  1004. if ($filter === null) {
  1005. $filter = DateTimeZone::ALL;
  1006. }
  1007. $identifiers = DateTimeZone::listIdentifiers($filter, $country);
  1008. }
  1009. if ($regex) {
  1010. foreach ($identifiers as $key => $tz) {
  1011. if (!preg_match($regex, $tz)) {
  1012. unset($identifiers[$key]);
  1013. }
  1014. }
  1015. }
  1016. if ($group) {
  1017. $return = array();
  1018. foreach ($identifiers as $key => $tz) {
  1019. $item = explode('/', $tz, 2);
  1020. if (isset($item[1])) {
  1021. $return[$item[0]][$tz] = $item[1];
  1022. } else {
  1023. $return[$item[0]] = array($tz => $item[0]);
  1024. }
  1025. }
  1026. return $return;
  1027. }
  1028. return array_combine($identifiers, $identifiers);
  1029. }
  1030. /**
  1031. * Multibyte wrapper for strftime.
  1032. *
  1033. * Handles utf8_encoding the result of strftime when necessary.
  1034. *
  1035. * @param string $format Format string.
  1036. * @param int $date Timestamp to format.
  1037. * @return string formatted string with correct encoding.
  1038. */
  1039. protected static function _strftime($format, $date) {
  1040. $format = strftime($format, $date);
  1041. $encoding = Configure::read('App.encoding');
  1042. if (!empty($encoding) && $encoding === 'UTF-8') {
  1043. if (function_exists('mb_check_encoding')) {
  1044. $valid = mb_check_encoding($format, $encoding);
  1045. } else {
  1046. $valid = Multibyte::checkMultibyte($format);
  1047. }
  1048. if (!$valid) {
  1049. $format = utf8_encode($format);
  1050. }
  1051. }
  1052. return $format;
  1053. }
  1054. }