PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/CakeTime.php

https://gitlab.com/manuperazafa/elsartenbackend
PHP | 1144 lines | 636 code | 98 blank | 410 comment | 131 complexity | 1065ae5664ca2d731018facbfce44f60 MD5 | raw file
  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. self::${$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 self::${$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. self::$_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', self::$_time)];
  143. }
  144. break;
  145. case 'A':
  146. $day = __dc('cake', 'day', 5);
  147. if (is_array($day)) {
  148. return $day[date('w', self::$_time)];
  149. }
  150. break;
  151. case 'c':
  152. $format = __dc('cake', 'd_t_fmt', 5);
  153. if ($format !== 'd_t_fmt') {
  154. return self::convertSpecifiers($format, self::$_time);
  155. }
  156. break;
  157. case 'C':
  158. return sprintf("%02d", date('Y', self::$_time) / 100);
  159. case 'D':
  160. return '%m/%d/%y';
  161. case 'e':
  162. if (DS === '/') {
  163. return '%e';
  164. }
  165. $day = date('j', self::$_time);
  166. if ($day < 10) {
  167. $day = ' ' . $day;
  168. }
  169. return $day;
  170. case 'eS' :
  171. return date('jS', self::$_time);
  172. case 'b':
  173. case 'h':
  174. $months = __dc('cake', 'abmon', 5);
  175. if (is_array($months)) {
  176. return $months[date('n', self::$_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', self::$_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', self::$_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', self::_translateSpecifier(array('%p', 'p')), $complete);
  201. }
  202. break;
  203. case 'R':
  204. return date('H:i', self::$_time);
  205. case 't':
  206. return "\t";
  207. case 'T':
  208. return '%H:%M:%S';
  209. case 'u':
  210. return ($weekDay = date('w', self::$_time)) ? $weekDay : 7;
  211. case 'x':
  212. $format = __dc('cake', 'd_fmt', 5);
  213. if ($format !== 'd_fmt') {
  214. return self::convertSpecifiers($format, self::$_time);
  215. }
  216. break;
  217. case 'X':
  218. $format = __dc('cake', 't_fmt', 5);
  219. if ($format !== 't_fmt') {
  220. return self::convertSpecifiers($format, self::$_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 = self::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 = intval($dateString);
  304. } elseif (
  305. $dateString instanceof DateTime &&
  306. $dateString->getTimezone()->getName() != date_default_timezone_get()
  307. ) {
  308. $clone = clone $dateString;
  309. $clone->setTimezone(new DateTimeZone(date_default_timezone_get()));
  310. $date = (int)$clone->format('U') + $clone->getOffset();
  311. } elseif ($dateString instanceof DateTime) {
  312. $date = (int)$dateString->format('U');
  313. } else {
  314. $date = strtotime($dateString);
  315. }
  316. if ($date === -1 || empty($date)) {
  317. return false;
  318. }
  319. if ($timezone === null) {
  320. $timezone = Configure::read('Config.timezone');
  321. }
  322. if ($timezone !== null) {
  323. return self::convert($date, $timezone);
  324. }
  325. return $date;
  326. }
  327. /**
  328. * Returns a nicely formatted date string for given Datetime string.
  329. *
  330. * See http://php.net/manual/en/function.strftime.php for information on formatting
  331. * using locale strings.
  332. *
  333. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  334. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  335. * @param string $format The format to use. If null, `TimeHelper::$niceFormat` is used
  336. * @return string Formatted date string
  337. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::nice
  338. */
  339. public static function nice($dateString = null, $timezone = null, $format = null) {
  340. if (!$dateString) {
  341. $dateString = time();
  342. }
  343. $date = self::fromString($dateString, $timezone);
  344. if (!$format) {
  345. $format = self::$niceFormat;
  346. }
  347. return self::_strftime(self::convertSpecifiers($format, $date), $date);
  348. }
  349. /**
  350. * Returns a formatted descriptive date string for given datetime string.
  351. *
  352. * If the given date is today, the returned string could be "Today, 16:54".
  353. * If the given date is tomorrow, the returned string could be "Tomorrow, 16:54".
  354. * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
  355. * If the given date is within next or last week, the returned string could be "On Thursday, 16:54".
  356. * If $dateString's year is the current year, the returned string does not
  357. * include mention of the year.
  358. *
  359. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  360. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  361. * @return string Described, relative date string
  362. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::niceShort
  363. */
  364. public static function niceShort($dateString = null, $timezone = null) {
  365. if (!$dateString) {
  366. $dateString = time();
  367. }
  368. $date = self::fromString($dateString, $timezone);
  369. if (self::isToday($dateString, $timezone)) {
  370. return __d('cake', 'Today, %s', self::_strftime("%H:%M", $date));
  371. }
  372. if (self::wasYesterday($dateString, $timezone)) {
  373. return __d('cake', 'Yesterday, %s', self::_strftime("%H:%M", $date));
  374. }
  375. if (self::isTomorrow($dateString, $timezone)) {
  376. return __d('cake', 'Tomorrow, %s', self::_strftime("%H:%M", $date));
  377. }
  378. $d = self::_strftime("%w", $date);
  379. $day = array(
  380. __d('cake', 'Sunday'),
  381. __d('cake', 'Monday'),
  382. __d('cake', 'Tuesday'),
  383. __d('cake', 'Wednesday'),
  384. __d('cake', 'Thursday'),
  385. __d('cake', 'Friday'),
  386. __d('cake', 'Saturday')
  387. );
  388. if (self::wasWithinLast('7 days', $dateString, $timezone)) {
  389. return sprintf('%s %s', $day[$d], self::_strftime(self::$niceShortFormat, $date));
  390. }
  391. if (self::isWithinNext('7 days', $dateString, $timezone)) {
  392. return __d('cake', 'On %s %s', $day[$d], self::_strftime(self::$niceShortFormat, $date));
  393. }
  394. $y = '';
  395. if (!self::isThisYear($date)) {
  396. $y = ' %Y';
  397. }
  398. return self::_strftime(self::convertSpecifiers("%b %eS{$y}, %H:%M", $date), $date);
  399. }
  400. /**
  401. * Returns a partial SQL string to search for all records between two dates.
  402. *
  403. * @param int|string|DateTime $begin UNIX timestamp, strtotime() valid string or DateTime object
  404. * @param int|string|DateTime $end UNIX timestamp, strtotime() valid string or DateTime object
  405. * @param string $fieldName Name of database field to compare with
  406. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  407. * @return string Partial SQL string.
  408. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::daysAsSql
  409. */
  410. public static function daysAsSql($begin, $end, $fieldName, $timezone = null) {
  411. $begin = self::fromString($begin, $timezone);
  412. $end = self::fromString($end, $timezone);
  413. $begin = date('Y-m-d', $begin) . ' 00:00:00';
  414. $end = date('Y-m-d', $end) . ' 23:59:59';
  415. return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
  416. }
  417. /**
  418. * Returns a partial SQL string to search for all records between two times
  419. * occurring on the same day.
  420. *
  421. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  422. * @param string $fieldName Name of database field to compare with
  423. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  424. * @return string Partial SQL string.
  425. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::dayAsSql
  426. */
  427. public static function dayAsSql($dateString, $fieldName, $timezone = null) {
  428. return self::daysAsSql($dateString, $dateString, $fieldName, $timezone);
  429. }
  430. /**
  431. * Returns true if given datetime string is today.
  432. *
  433. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  434. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  435. * @return bool True if datetime string is today
  436. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isToday
  437. */
  438. public static function isToday($dateString, $timezone = null) {
  439. $timestamp = self::fromString($dateString, $timezone);
  440. $now = self::fromString('now', $timezone);
  441. return date('Y-m-d', $timestamp) === date('Y-m-d', $now);
  442. }
  443. /**
  444. * Returns true if given datetime string is in the future.
  445. *
  446. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  447. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  448. * @return bool True if datetime string is in the future
  449. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isFuture
  450. */
  451. public static function isFuture($dateString, $timezone = null) {
  452. $timestamp = self::fromString($dateString, $timezone);
  453. return $timestamp > time();
  454. }
  455. /**
  456. * Returns true if given datetime string is in the past.
  457. *
  458. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  459. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  460. * @return bool True if datetime string is in the past
  461. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isPast
  462. */
  463. public static function isPast($dateString, $timezone = null) {
  464. $timestamp = self::fromString($dateString, $timezone);
  465. return $timestamp < time();
  466. }
  467. /**
  468. * Returns true if given datetime string is within this week.
  469. *
  470. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  471. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  472. * @return bool True if datetime string is within current week
  473. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisWeek
  474. */
  475. public static function isThisWeek($dateString, $timezone = null) {
  476. $timestamp = self::fromString($dateString, $timezone);
  477. $now = self::fromString('now', $timezone);
  478. return date('W o', $timestamp) === date('W o', $now);
  479. }
  480. /**
  481. * Returns true if given datetime string is within this month
  482. *
  483. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  484. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  485. * @return bool True if datetime string is within current month
  486. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisMonth
  487. */
  488. public static function isThisMonth($dateString, $timezone = null) {
  489. $timestamp = self::fromString($dateString, $timezone);
  490. $now = self::fromString('now', $timezone);
  491. return date('m Y', $timestamp) === date('m Y', $now);
  492. }
  493. /**
  494. * Returns true if given datetime string is within current year.
  495. *
  496. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  497. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  498. * @return bool True if datetime string is within current year
  499. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisYear
  500. */
  501. public static function isThisYear($dateString, $timezone = null) {
  502. $timestamp = self::fromString($dateString, $timezone);
  503. $now = self::fromString('now', $timezone);
  504. return date('Y', $timestamp) === date('Y', $now);
  505. }
  506. /**
  507. * Returns true if given datetime string was yesterday.
  508. *
  509. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  510. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  511. * @return bool True if datetime string was yesterday
  512. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::wasYesterday
  513. */
  514. public static function wasYesterday($dateString, $timezone = null) {
  515. $timestamp = self::fromString($dateString, $timezone);
  516. $yesterday = self::fromString('yesterday', $timezone);
  517. return date('Y-m-d', $timestamp) === date('Y-m-d', $yesterday);
  518. }
  519. /**
  520. * Returns true if given datetime string is tomorrow.
  521. *
  522. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  523. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  524. * @return bool True if datetime string was yesterday
  525. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isTomorrow
  526. */
  527. public static function isTomorrow($dateString, $timezone = null) {
  528. $timestamp = self::fromString($dateString, $timezone);
  529. $tomorrow = self::fromString('tomorrow', $timezone);
  530. return date('Y-m-d', $timestamp) === date('Y-m-d', $tomorrow);
  531. }
  532. /**
  533. * Returns the quarter
  534. *
  535. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  536. * @param bool $range if true returns a range in Y-m-d format
  537. * @return mixed 1, 2, 3, or 4 quarter of year or array if $range true
  538. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toQuarter
  539. */
  540. public static function toQuarter($dateString, $range = false) {
  541. $time = self::fromString($dateString);
  542. $date = ceil(date('m', $time) / 3);
  543. if ($range === false) {
  544. return $date;
  545. }
  546. $year = date('Y', $time);
  547. switch ($date) {
  548. case 1:
  549. return array($year . '-01-01', $year . '-03-31');
  550. case 2:
  551. return array($year . '-04-01', $year . '-06-30');
  552. case 3:
  553. return array($year . '-07-01', $year . '-09-30');
  554. case 4:
  555. return array($year . '-10-01', $year . '-12-31');
  556. }
  557. }
  558. /**
  559. * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
  560. *
  561. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  562. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  563. * @return int Unix timestamp
  564. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toUnix
  565. */
  566. public static function toUnix($dateString, $timezone = null) {
  567. return self::fromString($dateString, $timezone);
  568. }
  569. /**
  570. * Returns a formatted date in server's timezone.
  571. *
  572. * If a DateTime object is given or the dateString has a timezone
  573. * segment, the timezone parameter will be ignored.
  574. *
  575. * If no timezone parameter is given and no DateTime object, the passed $dateString will be
  576. * considered to be in the UTC timezone.
  577. *
  578. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  579. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  580. * @param string $format date format string
  581. * @return mixed Formatted date
  582. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toServer
  583. */
  584. public static function toServer($dateString, $timezone = null, $format = 'Y-m-d H:i:s') {
  585. if ($timezone === null) {
  586. $timezone = new DateTimeZone('UTC');
  587. } elseif (is_string($timezone)) {
  588. $timezone = new DateTimeZone($timezone);
  589. } elseif (!($timezone instanceof DateTimeZone)) {
  590. return false;
  591. }
  592. if ($dateString instanceof DateTime) {
  593. $date = $dateString;
  594. } elseif (is_int($dateString) || is_numeric($dateString)) {
  595. $dateString = (int)$dateString;
  596. $date = new DateTime('@' . $dateString);
  597. $date->setTimezone($timezone);
  598. } else {
  599. $date = new DateTime($dateString, $timezone);
  600. }
  601. $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
  602. return $date->format($format);
  603. }
  604. /**
  605. * Returns a date formatted for Atom RSS feeds.
  606. *
  607. * @param string $dateString Datetime string or Unix timestamp
  608. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  609. * @return string Formatted date string
  610. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toAtom
  611. */
  612. public static function toAtom($dateString, $timezone = null) {
  613. return date('Y-m-d\TH:i:s\Z', self::fromString($dateString, $timezone));
  614. }
  615. /**
  616. * Formats date for RSS feeds
  617. *
  618. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  619. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  620. * @return string Formatted date string
  621. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toRSS
  622. */
  623. public static function toRSS($dateString, $timezone = null) {
  624. $date = self::fromString($dateString, $timezone);
  625. if ($timezone === null) {
  626. return date("r", $date);
  627. }
  628. $userOffset = $timezone;
  629. if (!is_numeric($timezone)) {
  630. if (!is_object($timezone)) {
  631. $timezone = new DateTimeZone($timezone);
  632. }
  633. $currentDate = new DateTime('@' . $date);
  634. $currentDate->setTimezone($timezone);
  635. $userOffset = $timezone->getOffset($currentDate) / 60 / 60;
  636. }
  637. $timezone = '+0000';
  638. if ($userOffset != 0) {
  639. $hours = (int)floor(abs($userOffset));
  640. $minutes = (int)(fmod(abs($userOffset), $hours) * 60);
  641. $timezone = ($userOffset < 0 ? '-' : '+') . str_pad($hours, 2, '0', STR_PAD_LEFT) . str_pad($minutes, 2, '0', STR_PAD_LEFT);
  642. }
  643. return date('D, d M Y H:i:s', $date) . ' ' . $timezone;
  644. }
  645. /**
  646. * Returns either a relative or a formatted absolute date depending
  647. * on the difference between the current time and given datetime.
  648. * $datetime should be in a *strtotime* - parsable format, like MySQL's datetime datatype.
  649. *
  650. * ### Options:
  651. *
  652. * - `format` => a fall back format if the relative time is longer than the duration specified by end
  653. * - `accuracy` => Specifies how accurate the date should be described (array)
  654. * - year => The format if years > 0 (default "day")
  655. * - month => The format if months > 0 (default "day")
  656. * - week => The format if weeks > 0 (default "day")
  657. * - day => The format if weeks > 0 (default "hour")
  658. * - hour => The format if hours > 0 (default "minute")
  659. * - minute => The format if minutes > 0 (default "minute")
  660. * - second => The format if seconds > 0 (default "second")
  661. * - `end` => The end of relative time telling
  662. * - `relativeString` => The printf compatible string when outputting relative time
  663. * - `absoluteString` => The printf compatible string when outputting absolute time
  664. * - `userOffset` => Users offset from GMT (in hours) *Deprecated* use timezone intead.
  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. $format = self::$wordFormat;
  687. $end = self::$wordEnd;
  688. $relativeString = __d('cake', '%s ago');
  689. $absoluteString = __d('cake', 'on %s');
  690. $accuracy = self::$wordAccuracy;
  691. if (is_array($options)) {
  692. if (isset($options['timezone'])) {
  693. $timezone = $options['timezone'];
  694. } elseif (isset($options['userOffset'])) {
  695. $timezone = $options['userOffset'];
  696. }
  697. if (isset($options['accuracy'])) {
  698. if (is_array($options['accuracy'])) {
  699. $accuracy = array_merge($accuracy, $options['accuracy']);
  700. } else {
  701. foreach ($accuracy as $key => $level) {
  702. $accuracy[$key] = $options['accuracy'];
  703. }
  704. }
  705. }
  706. if (isset($options['format'])) {
  707. $format = $options['format'];
  708. }
  709. if (isset($options['end'])) {
  710. $end = $options['end'];
  711. }
  712. if (isset($options['relativeString'])) {
  713. $relativeString = $options['relativeString'];
  714. unset($options['relativeString']);
  715. }
  716. if (isset($options['absoluteString'])) {
  717. $absoluteString = $options['absoluteString'];
  718. unset($options['absoluteString']);
  719. }
  720. unset($options['end'], $options['format']);
  721. } else {
  722. $format = $options;
  723. }
  724. $now = self::fromString(time(), $timezone);
  725. $inSeconds = self::fromString($dateTime, $timezone);
  726. $backwards = ($inSeconds > $now);
  727. $futureTime = $now;
  728. $pastTime = $inSeconds;
  729. if ($backwards) {
  730. $futureTime = $inSeconds;
  731. $pastTime = $now;
  732. }
  733. $diff = $futureTime - $pastTime;
  734. if (!$diff) {
  735. return __d('cake', 'just now', 'just now');
  736. }
  737. if ($diff > abs($now - self::fromString($end))) {
  738. return sprintf($absoluteString, date($format, $inSeconds));
  739. }
  740. // If more than a week, then take into account the length of months
  741. if ($diff >= 604800) {
  742. list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime));
  743. list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime));
  744. $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
  745. $years = $future['Y'] - $past['Y'];
  746. $months = $future['m'] + ((12 * $years) - $past['m']);
  747. if ($months >= 12) {
  748. $years = floor($months / 12);
  749. $months = $months - ($years * 12);
  750. }
  751. if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] === 1) {
  752. $years--;
  753. }
  754. if ($future['d'] >= $past['d']) {
  755. $days = $future['d'] - $past['d'];
  756. } else {
  757. $daysInPastMonth = date('t', $pastTime);
  758. $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
  759. if (!$backwards) {
  760. $days = ($daysInPastMonth - $past['d']) + $future['d'];
  761. } else {
  762. $days = ($daysInFutureMonth - $past['d']) + $future['d'];
  763. }
  764. if ($future['m'] != $past['m']) {
  765. $months--;
  766. }
  767. }
  768. if (!$months && $years >= 1 && $diff < ($years * 31536000)) {
  769. $months = 11;
  770. $years--;
  771. }
  772. if ($months >= 12) {
  773. $years = $years + 1;
  774. $months = $months - 12;
  775. }
  776. if ($days >= 7) {
  777. $weeks = floor($days / 7);
  778. $days = $days - ($weeks * 7);
  779. }
  780. } else {
  781. $years = $months = $weeks = 0;
  782. $days = floor($diff / 86400);
  783. $diff = $diff - ($days * 86400);
  784. $hours = floor($diff / 3600);
  785. $diff = $diff - ($hours * 3600);
  786. $minutes = floor($diff / 60);
  787. $diff = $diff - ($minutes * 60);
  788. $seconds = $diff;
  789. }
  790. $fWord = $accuracy['second'];
  791. if ($years > 0) {
  792. $fWord = $accuracy['year'];
  793. } elseif (abs($months) > 0) {
  794. $fWord = $accuracy['month'];
  795. } elseif (abs($weeks) > 0) {
  796. $fWord = $accuracy['week'];
  797. } elseif (abs($days) > 0) {
  798. $fWord = $accuracy['day'];
  799. } elseif (abs($hours) > 0) {
  800. $fWord = $accuracy['hour'];
  801. } elseif (abs($minutes) > 0) {
  802. $fWord = $accuracy['minute'];
  803. }
  804. $fNum = str_replace(array('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), array(1, 2, 3, 4, 5, 6, 7), $fWord);
  805. $relativeDate = '';
  806. if ($fNum >= 1 && $years > 0) {
  807. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d year', '%d years', $years, $years);
  808. }
  809. if ($fNum >= 2 && $months > 0) {
  810. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months);
  811. }
  812. if ($fNum >= 3 && $weeks > 0) {
  813. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks);
  814. }
  815. if ($fNum >= 4 && $days > 0) {
  816. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days);
  817. }
  818. if ($fNum >= 5 && $hours > 0) {
  819. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours);
  820. }
  821. if ($fNum >= 6 && $minutes > 0) {
  822. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes);
  823. }
  824. if ($fNum >= 7 && $seconds > 0) {
  825. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d second', '%d seconds', $seconds, $seconds);
  826. }
  827. // When time has passed
  828. if (!$backwards && $relativeDate) {
  829. return sprintf($relativeString, $relativeDate);
  830. }
  831. if (!$backwards) {
  832. $aboutAgo = array(
  833. 'second' => __d('cake', 'about a second ago'),
  834. 'minute' => __d('cake', 'about a minute ago'),
  835. 'hour' => __d('cake', 'about an hour ago'),
  836. 'day' => __d('cake', 'about a day ago'),
  837. 'week' => __d('cake', 'about a week ago'),
  838. 'year' => __d('cake', 'about a year ago')
  839. );
  840. return $aboutAgo[$fWord];
  841. }
  842. // When time is to come
  843. if (!$relativeDate) {
  844. $aboutIn = 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. return $aboutIn[$fWord];
  853. }
  854. return $relativeDate;
  855. }
  856. /**
  857. * Returns true if specified datetime was within the interval specified, else false.
  858. *
  859. * @param string|int $timeInterval the numeric value with space then time type.
  860. * Example of valid types: 6 hours, 2 days, 1 minute.
  861. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  862. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  863. * @return bool
  864. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::wasWithinLast
  865. */
  866. public static function wasWithinLast($timeInterval, $dateString, $timezone = null) {
  867. $tmp = str_replace(' ', '', $timeInterval);
  868. if (is_numeric($tmp)) {
  869. $timeInterval = $tmp . ' ' . __d('cake', 'days');
  870. }
  871. $date = self::fromString($dateString, $timezone);
  872. $interval = self::fromString('-' . $timeInterval);
  873. $now = self::fromString('now', $timezone);
  874. return $date >= $interval && $date <= $now;
  875. }
  876. /**
  877. * Returns true if specified datetime is within the interval specified, else false.
  878. *
  879. * @param string|int $timeInterval the numeric value with space then time type.
  880. * Example of valid types: 6 hours, 2 days, 1 minute.
  881. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  882. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  883. * @return bool
  884. */
  885. public static function isWithinNext($timeInterval, $dateString, $timezone = null) {
  886. $tmp = str_replace(' ', '', $timeInterval);
  887. if (is_numeric($tmp)) {
  888. $timeInterval = $tmp . ' ' . __d('cake', 'days');
  889. }
  890. $date = self::fromString($dateString, $timezone);
  891. $interval = self::fromString('+' . $timeInterval);
  892. $now = self::fromString('now', $timezone);
  893. return $date <= $interval && $date >= $now;
  894. }
  895. /**
  896. * Returns gmt as a UNIX timestamp.
  897. *
  898. * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
  899. * @return int UNIX timestamp
  900. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::gmt
  901. */
  902. public static function gmt($dateString = null) {
  903. $time = time();
  904. if ($dateString) {
  905. $time = self::fromString($dateString);
  906. }
  907. return gmmktime(
  908. intval(date('G', $time)),
  909. intval(date('i', $time)),
  910. intval(date('s', $time)),
  911. intval(date('n', $time)),
  912. intval(date('j', $time)),
  913. intval(date('Y', $time))
  914. );
  915. }
  916. /**
  917. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  918. * This function also accepts a time string and a format string as first and second parameters.
  919. * In that case this function behaves as a wrapper for TimeHelper::i18nFormat()
  920. *
  921. * ## Examples
  922. *
  923. * Create localized & formatted time:
  924. *
  925. * {{{
  926. * CakeTime::format('2012-02-15', '%m-%d-%Y'); // returns 02-15-2012
  927. * CakeTime::format('2012-02-15 23:01:01', '%c'); // returns preferred date and time based on configured locale
  928. * CakeTime::format('0000-00-00', '%d-%m-%Y', 'N/A'); // return N/A becuase an invalid date was passed
  929. * CakeTime::format('2012-02-15 23:01:01', '%c', 'N/A', 'America/New_York'); // converts passed date to timezone
  930. * }}}
  931. *
  932. * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object (or a date format string)
  933. * @param int|string|DateTime $format date format string (or UNIX timestamp, strtotime() valid string or DateTime object)
  934. * @param bool|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
  935. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  936. * @return string Formatted date string
  937. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::format
  938. * @see CakeTime::i18nFormat()
  939. */
  940. public static function format($date, $format = null, $default = false, $timezone = null) {
  941. //Backwards compatible params re-order test
  942. $time = self::fromString($format, $timezone);
  943. if ($time === false) {
  944. return self::i18nFormat($date, $format, $default, $timezone);
  945. }
  946. return date($date, $time);
  947. }
  948. /**
  949. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  950. * It takes into account the default date format for the current language if a LC_TIME file is used.
  951. *
  952. * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object
  953. * @param string $format strftime format string.
  954. * @param bool|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
  955. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  956. * @return string Formatted and translated date string
  957. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::i18nFormat
  958. */
  959. public static function i18nFormat($date, $format = null, $default = false, $timezone = null) {
  960. $date = self::fromString($date, $timezone);
  961. if ($date === false && $default !== false) {
  962. return $default;
  963. }
  964. if ($date === false) {
  965. return '';
  966. }
  967. if (empty($format)) {
  968. $format = '%x';
  969. }
  970. return self::_strftime(self::convertSpecifiers($format, $date), $date);
  971. }
  972. /**
  973. * Get list of timezone identifiers
  974. *
  975. * @param int|string $filter A regex to filter identifier
  976. * Or one of DateTimeZone class constants (PHP 5.3 and above)
  977. * @param string $country A two-letter ISO 3166-1 compatible country code.
  978. * This option is only used when $filter is set to DateTimeZone::PER_COUNTRY (available only in PHP 5.3 and above)
  979. * @param bool $group If true (default value) groups the identifiers list by primary region
  980. * @return array List of timezone identifiers
  981. * @since 2.2
  982. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::listTimezones
  983. */
  984. public static function listTimezones($filter = null, $country = null, $group = true) {
  985. $regex = null;
  986. if (is_string($filter)) {
  987. $regex = $filter;
  988. $filter = null;
  989. }
  990. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  991. if ($regex === null) {
  992. $regex = '#^((Africa|America|Antartica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC)#';
  993. }
  994. $identifiers = DateTimeZone::listIdentifiers();
  995. } else {
  996. if ($filter === null) {
  997. $filter = DateTimeZone::ALL;
  998. }
  999. $identifiers = DateTimeZone::listIdentifiers($filter, $country);
  1000. }
  1001. if ($regex) {
  1002. foreach ($identifiers as $key => $tz) {
  1003. if (!preg_match($regex, $tz)) {
  1004. unset($identifiers[$key]);
  1005. }
  1006. }
  1007. }
  1008. if ($group) {
  1009. $return = array();
  1010. foreach ($identifiers as $key => $tz) {
  1011. $item = explode('/', $tz, 2);
  1012. if (isset($item[1])) {
  1013. $return[$item[0]][$tz] = $item[1];
  1014. } else {
  1015. $return[$item[0]] = array($tz => $item[0]);
  1016. }
  1017. }
  1018. return $return;
  1019. }
  1020. return array_combine($identifiers, $identifiers);
  1021. }
  1022. /**
  1023. * Multibyte wrapper for strftime.
  1024. *
  1025. * Handles utf8_encoding the result of strftime when necessary.
  1026. *
  1027. * @param string $format Format string.
  1028. * @param int $date Timestamp to format.
  1029. * @return string formatted string with correct encoding.
  1030. */
  1031. protected static function _strftime($format, $date) {
  1032. $format = strftime($format, $date);
  1033. $encoding = Configure::read('App.encoding');
  1034. if (!empty($encoding) && $encoding === 'UTF-8') {
  1035. if (function_exists('mb_check_encoding')) {
  1036. $valid = mb_check_encoding($format, $encoding);
  1037. } else {
  1038. $valid = !Multibyte::checkMultibyte($format);
  1039. }
  1040. if (!$valid) {
  1041. $format = utf8_encode($format);
  1042. }
  1043. }
  1044. return $format;
  1045. }
  1046. }