CakeTime.php 35 KB

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