PageRenderTime 58ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Utility/CakeTime.php

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