Time.php 38 KB

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