PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/View/Helper/TimeHelper.php

https://bitbucket.org/udeshika/fake_twitter
PHP | 780 lines | 431 code | 63 blank | 286 comment | 102 complexity | d9e28eaa88a2a2d654df7621e801f09a MD5 | raw file
  1. <?php
  2. /**
  3. * Time Helper class file.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, 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-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package Cake.View.Helper
  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. App::uses('AppHelper', 'View/Helper');
  21. /**
  22. * Time Helper class for easy use of time data.
  23. *
  24. * Manipulation of time data.
  25. *
  26. * @package Cake.View.Helper
  27. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html
  28. */
  29. class TimeHelper extends AppHelper {
  30. /**
  31. * The format to use when formatting a time using `TimeHelper::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 TimeHelper::format()
  38. */
  39. public $niceFormat = '%a, %b %eS %Y, %H:%M';
  40. /**
  41. * Constructor
  42. *
  43. * @param View $View the view object the helper is attached to.
  44. * @param array $settings Settings array Settings array
  45. */
  46. public function __construct(View $View, $settings = array()) {
  47. if (isset($settings['niceFormat'])) {
  48. $this->niceFormat = $settings['niceFormat'];
  49. }
  50. parent::__construct($View, $settings);
  51. }
  52. /**
  53. * Converts a string representing the format for the function strftime and returns a
  54. * windows safe and i18n aware format.
  55. *
  56. * @param string $format Format with specifiers for strftime function.
  57. * Accepts the special specifier %S which mimics the modifier S for date()
  58. * @param string $time UNIX timestamp
  59. * @return string windows safe and date() function compatible format for strftime
  60. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  61. */
  62. public function convertSpecifiers($format, $time = null) {
  63. if (!$time) {
  64. $time = time();
  65. }
  66. $this->__time = $time;
  67. return preg_replace_callback('/\%(\w+)/', array($this, '_translateSpecifier'), $format);
  68. }
  69. /**
  70. * Auxiliary function to translate a matched specifier element from a regular expression into
  71. * a windows safe and i18n aware specifier
  72. *
  73. * @param array $specifier match from regular expression
  74. * @return string converted element
  75. */
  76. protected function _translateSpecifier($specifier) {
  77. switch ($specifier[1]) {
  78. case 'a':
  79. $abday = __dc('cake', 'abday', 5);
  80. if (is_array($abday)) {
  81. return $abday[date('w', $this->__time)];
  82. }
  83. break;
  84. case 'A':
  85. $day = __dc('cake', 'day', 5);
  86. if (is_array($day)) {
  87. return $day[date('w', $this->__time)];
  88. }
  89. break;
  90. case 'c':
  91. $format = __dc('cake', 'd_t_fmt', 5);
  92. if ($format != 'd_t_fmt') {
  93. return $this->convertSpecifiers($format, $this->__time);
  94. }
  95. break;
  96. case 'C':
  97. return sprintf("%02d", date('Y', $this->__time) / 100);
  98. case 'D':
  99. return '%m/%d/%y';
  100. case 'e':
  101. if (DS === '/') {
  102. return '%e';
  103. }
  104. $day = date('j', $this->__time);
  105. if ($day < 10) {
  106. $day = ' ' . $day;
  107. }
  108. return $day;
  109. case 'eS' :
  110. return date('jS', $this->__time);
  111. case 'b':
  112. case 'h':
  113. $months = __dc('cake', 'abmon', 5);
  114. if (is_array($months)) {
  115. return $months[date('n', $this->__time) -1];
  116. }
  117. return '%b';
  118. case 'B':
  119. $months = __dc('cake', 'mon', 5);
  120. if (is_array($months)) {
  121. return $months[date('n', $this->__time) -1];
  122. }
  123. break;
  124. case 'n':
  125. return "\n";
  126. case 'p':
  127. case 'P':
  128. $default = array('am' => 0, 'pm' => 1);
  129. $meridiem = $default[date('a', $this->__time)];
  130. $format = __dc('cake', 'am_pm', 5);
  131. if (is_array($format)) {
  132. $meridiem = $format[$meridiem];
  133. return ($specifier[1] == 'P') ? strtolower($meridiem) : strtoupper($meridiem);
  134. }
  135. break;
  136. case 'r':
  137. $complete = __dc('cake', 't_fmt_ampm', 5);
  138. if ($complete != 't_fmt_ampm') {
  139. return str_replace('%p', $this->_translateSpecifier(array('%p', 'p')), $complete);
  140. }
  141. break;
  142. case 'R':
  143. return date('H:i', $this->__time);
  144. case 't':
  145. return "\t";
  146. case 'T':
  147. return '%H:%M:%S';
  148. case 'u':
  149. return ($weekDay = date('w', $this->__time)) ? $weekDay : 7;
  150. case 'x':
  151. $format = __dc('cake', 'd_fmt', 5);
  152. if ($format != 'd_fmt') {
  153. return $this->convertSpecifiers($format, $this->__time);
  154. }
  155. break;
  156. case 'X':
  157. $format = __dc('cake', 't_fmt', 5);
  158. if ($format != 't_fmt') {
  159. return $this->convertSpecifiers($format, $this->__time);
  160. }
  161. break;
  162. }
  163. return $specifier[0];
  164. }
  165. /**
  166. * Converts given time (in server's time zone) to user's local time, given his/her offset from GMT.
  167. *
  168. * @param string $serverTime UNIX timestamp
  169. * @param integer $userOffset User's offset from GMT (in hours)
  170. * @return integer UNIX timestamp
  171. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  172. */
  173. public function convert($serverTime, $userOffset) {
  174. $serverOffset = $this->serverOffset();
  175. $gmtTime = $serverTime - $serverOffset;
  176. $userTime = $gmtTime + $userOffset * (60*60);
  177. return $userTime;
  178. }
  179. /**
  180. * Returns server's offset from GMT in seconds.
  181. *
  182. * @return integer Offset
  183. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  184. */
  185. public function serverOffset() {
  186. return date('Z', time());
  187. }
  188. /**
  189. * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
  190. *
  191. * @param string $dateString Datetime string
  192. * @param integer $userOffset User's offset from GMT (in hours)
  193. * @return string Parsed timestamp
  194. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  195. */
  196. public function fromString($dateString, $userOffset = null) {
  197. if (empty($dateString)) {
  198. return false;
  199. }
  200. if (is_integer($dateString) || is_numeric($dateString)) {
  201. $date = intval($dateString);
  202. } else {
  203. $date = strtotime($dateString);
  204. }
  205. if ($userOffset !== null) {
  206. return $this->convert($date, $userOffset);
  207. }
  208. if ($date === -1) {
  209. return false;
  210. }
  211. return $date;
  212. }
  213. /**
  214. * Returns a nicely formatted date string for given Datetime string.
  215. *
  216. * See http://php.net/manual/en/function.strftime.php for information on formatting
  217. * using locale strings.
  218. *
  219. * @param string $dateString Datetime string or Unix timestamp
  220. * @param integer $userOffset User's offset from GMT (in hours)
  221. * @param string $format The format to use. If null, `TimeHelper::$niceFormat` is used
  222. * @return string Formatted date string
  223. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  224. */
  225. public function nice($dateString = null, $userOffset = null, $format = null) {
  226. if ($dateString != null) {
  227. $date = $this->fromString($dateString, $userOffset);
  228. } else {
  229. $date = time();
  230. }
  231. if (!$format) {
  232. $format = $this->niceFormat;
  233. }
  234. $format = $this->convertSpecifiers($format, $date);
  235. return $this->_strftime($format, $date);
  236. }
  237. /**
  238. * Returns a formatted descriptive date string for given datetime string.
  239. *
  240. * If the given date is today, the returned string could be "Today, 16:54".
  241. * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
  242. * If $dateString's year is the current year, the returned string does not
  243. * include mention of the year.
  244. *
  245. * @param string $dateString Datetime string or Unix timestamp
  246. * @param integer $userOffset User's offset from GMT (in hours)
  247. * @return string Described, relative date string
  248. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  249. */
  250. public function niceShort($dateString = null, $userOffset = null) {
  251. $date = $dateString ? $this->fromString($dateString, $userOffset) : time();
  252. $y = $this->isThisYear($date) ? '' : ' %Y';
  253. if ($this->isToday($dateString, $userOffset)) {
  254. $ret = __d('cake', 'Today, %s', $this->_strftime("%H:%M", $date));
  255. } elseif ($this->wasYesterday($dateString, $userOffset)) {
  256. $ret = __d('cake', 'Yesterday, %s', $this->_strftime("%H:%M", $date));
  257. } else {
  258. $format = $this->convertSpecifiers("%b %eS{$y}, %H:%M", $date);
  259. $ret = $this->_strftime($format, $date);
  260. }
  261. return $ret;
  262. }
  263. /**
  264. * Returns a partial SQL string to search for all records between two dates.
  265. *
  266. * @param string $begin Datetime string or Unix timestamp
  267. * @param string $end Datetime string or Unix timestamp
  268. * @param string $fieldName Name of database field to compare with
  269. * @param integer $userOffset User's offset from GMT (in hours)
  270. * @return string Partial SQL string.
  271. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  272. */
  273. public function daysAsSql($begin, $end, $fieldName, $userOffset = null) {
  274. $begin = $this->fromString($begin, $userOffset);
  275. $end = $this->fromString($end, $userOffset);
  276. $begin = date('Y-m-d', $begin) . ' 00:00:00';
  277. $end = date('Y-m-d', $end) . ' 23:59:59';
  278. return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
  279. }
  280. /**
  281. * Returns a partial SQL string to search for all records between two times
  282. * occurring on the same day.
  283. *
  284. * @param string $dateString Datetime string or Unix timestamp
  285. * @param string $fieldName Name of database field to compare with
  286. * @param integer $userOffset User's offset from GMT (in hours)
  287. * @return string Partial SQL string.
  288. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  289. */
  290. public function dayAsSql($dateString, $fieldName, $userOffset = null) {
  291. $date = $this->fromString($dateString, $userOffset);
  292. return $this->daysAsSql($dateString, $dateString, $fieldName);
  293. }
  294. /**
  295. * Returns true if given datetime string is today.
  296. *
  297. * @param string $dateString Datetime string or Unix timestamp
  298. * @param integer $userOffset User's offset from GMT (in hours)
  299. * @return boolean True if datetime string is today
  300. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  301. */
  302. public function isToday($dateString, $userOffset = null) {
  303. $date = $this->fromString($dateString, $userOffset);
  304. return date('Y-m-d', $date) == date('Y-m-d', time());
  305. }
  306. /**
  307. * Returns true if given datetime string is within this week.
  308. *
  309. * @param string $dateString
  310. * @param integer $userOffset User's offset from GMT (in hours)
  311. * @return boolean True if datetime string is within current week
  312. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  313. */
  314. public function isThisWeek($dateString, $userOffset = null) {
  315. $date = $this->fromString($dateString, $userOffset);
  316. return date('W o', $date) == date('W o', time());
  317. }
  318. /**
  319. * Returns true if given datetime string is within this month
  320. * @param string $dateString
  321. * @param integer $userOffset User's offset from GMT (in hours)
  322. * @return boolean True if datetime string is within current month
  323. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  324. */
  325. public function isThisMonth($dateString, $userOffset = null) {
  326. $date = $this->fromString($dateString);
  327. return date('m Y', $date) == date('m Y', time());
  328. }
  329. /**
  330. * Returns true if given datetime string is within current year.
  331. *
  332. * @param string $dateString Datetime string or Unix timestamp
  333. * @param integer $userOffset User's offset from GMT (in hours)
  334. * @return boolean True if datetime string is within current year
  335. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  336. */
  337. public function isThisYear($dateString, $userOffset = null) {
  338. $date = $this->fromString($dateString, $userOffset);
  339. return date('Y', $date) == date('Y', time());
  340. }
  341. /**
  342. * Returns true if given datetime string was yesterday.
  343. *
  344. * @param string $dateString Datetime string or Unix timestamp
  345. * @param integer $userOffset User's offset from GMT (in hours)
  346. * @return boolean True if datetime string was yesterday
  347. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  348. *
  349. */
  350. public function wasYesterday($dateString, $userOffset = null) {
  351. $date = $this->fromString($dateString, $userOffset);
  352. return date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday'));
  353. }
  354. /**
  355. * Returns true if given datetime string is tomorrow.
  356. *
  357. * @param string $dateString Datetime string or Unix timestamp
  358. * @param integer $userOffset User's offset from GMT (in hours)
  359. * @return boolean True if datetime string was yesterday
  360. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  361. */
  362. public function isTomorrow($dateString, $userOffset = null) {
  363. $date = $this->fromString($dateString, $userOffset);
  364. return date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow'));
  365. }
  366. /**
  367. * Returns the quarter
  368. *
  369. * @param string $dateString
  370. * @param boolean $range if true returns a range in Y-m-d format
  371. * @return mixed 1, 2, 3, or 4 quarter of year or array if $range true
  372. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  373. */
  374. public function toQuarter($dateString, $range = false) {
  375. $time = $this->fromString($dateString);
  376. $date = ceil(date('m', $time) / 3);
  377. if ($range === true) {
  378. $range = 'Y-m-d';
  379. }
  380. if ($range !== false) {
  381. $year = date('Y', $time);
  382. switch ($date) {
  383. case 1:
  384. $date = array($year.'-01-01', $year.'-03-31');
  385. break;
  386. case 2:
  387. $date = array($year.'-04-01', $year.'-06-30');
  388. break;
  389. case 3:
  390. $date = array($year.'-07-01', $year.'-09-30');
  391. break;
  392. case 4:
  393. $date = array($year.'-10-01', $year.'-12-31');
  394. break;
  395. }
  396. }
  397. return $date;
  398. }
  399. /**
  400. * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
  401. *
  402. * @param string $dateString Datetime string to be represented as a Unix timestamp
  403. * @param integer $userOffset User's offset from GMT (in hours)
  404. * @return integer Unix timestamp
  405. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  406. */
  407. public function toUnix($dateString, $userOffset = null) {
  408. return $this->fromString($dateString, $userOffset);
  409. }
  410. /**
  411. * Returns a date formatted for Atom RSS feeds.
  412. *
  413. * @param string $dateString Datetime string or Unix timestamp
  414. * @param integer $userOffset User's offset from GMT (in hours)
  415. * @return string Formatted date string
  416. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  417. */
  418. public function toAtom($dateString, $userOffset = null) {
  419. $date = $this->fromString($dateString, $userOffset);
  420. return date('Y-m-d\TH:i:s\Z', $date);
  421. }
  422. /**
  423. * Formats date for RSS feeds
  424. *
  425. * @param string $dateString Datetime string or Unix timestamp
  426. * @param integer $userOffset User's offset from GMT (in hours)
  427. * @return string Formatted date string
  428. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  429. */
  430. public function toRSS($dateString, $userOffset = null) {
  431. $date = $this->fromString($dateString, $userOffset);
  432. if (!is_null($userOffset)) {
  433. if ($userOffset == 0) {
  434. $timezone = '+0000';
  435. } else {
  436. $hours = (int) floor(abs($userOffset));
  437. $minutes = (int) (fmod(abs($userOffset), $hours) * 60);
  438. $timezone = ($userOffset < 0 ? '-' : '+') . str_pad($hours, 2, '0', STR_PAD_LEFT) . str_pad($minutes, 2, '0', STR_PAD_LEFT);
  439. }
  440. return date('D, d M Y H:i:s', $date) . ' ' . $timezone;
  441. }
  442. return date("r", $date);
  443. }
  444. /**
  445. * Returns either a relative date or a formatted date depending
  446. * on the difference between the current time and given datetime.
  447. * $datetime should be in a <i>strtotime</i> - parsable format, like MySQL's datetime datatype.
  448. *
  449. * ### Options:
  450. *
  451. * - `format` => a fall back format if the relative time is longer than the duration specified by end
  452. * - `end` => The end of relative time telling
  453. * - `userOffset` => Users offset from GMT (in hours)
  454. *
  455. * Relative dates look something like this:
  456. * 3 weeks, 4 days ago
  457. * 15 seconds ago
  458. *
  459. * Default date formatting is d/m/yy e.g: on 18/2/09
  460. *
  461. * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
  462. * like 'Posted ' before the function output.
  463. *
  464. * @param string $dateTime Datetime string or Unix timestamp
  465. * @param array $options Default format if timestamp is used in $dateString
  466. * @return string Relative time string.
  467. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  468. */
  469. public function timeAgoInWords($dateTime, $options = array()) {
  470. $userOffset = null;
  471. if (is_array($options) && isset($options['userOffset'])) {
  472. $userOffset = $options['userOffset'];
  473. }
  474. $now = time();
  475. if (!is_null($userOffset)) {
  476. $now = $this->convert(time(), $userOffset);
  477. }
  478. $inSeconds = $this->fromString($dateTime, $userOffset);
  479. $backwards = ($inSeconds > $now);
  480. $format = 'j/n/y';
  481. $end = '+1 month';
  482. if (is_array($options)) {
  483. if (isset($options['format'])) {
  484. $format = $options['format'];
  485. unset($options['format']);
  486. }
  487. if (isset($options['end'])) {
  488. $end = $options['end'];
  489. unset($options['end']);
  490. }
  491. } else {
  492. $format = $options;
  493. }
  494. if ($backwards) {
  495. $futureTime = $inSeconds;
  496. $pastTime = $now;
  497. } else {
  498. $futureTime = $now;
  499. $pastTime = $inSeconds;
  500. }
  501. $diff = $futureTime - $pastTime;
  502. // If more than a week, then take into account the length of months
  503. if ($diff >= 604800) {
  504. $current = array();
  505. $date = array();
  506. list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime));
  507. list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime));
  508. $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
  509. if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) {
  510. $months = 0;
  511. $years = 0;
  512. } else {
  513. if ($future['Y'] == $past['Y']) {
  514. $months = $future['m'] - $past['m'];
  515. } else {
  516. $years = $future['Y'] - $past['Y'];
  517. $months = $future['m'] + ((12 * $years) - $past['m']);
  518. if ($months >= 12) {
  519. $years = floor($months / 12);
  520. $months = $months - ($years * 12);
  521. }
  522. if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) {
  523. $years --;
  524. }
  525. }
  526. }
  527. if ($future['d'] >= $past['d']) {
  528. $days = $future['d'] - $past['d'];
  529. } else {
  530. $daysInPastMonth = date('t', $pastTime);
  531. $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
  532. if (!$backwards) {
  533. $days = ($daysInPastMonth - $past['d']) + $future['d'];
  534. } else {
  535. $days = ($daysInFutureMonth - $past['d']) + $future['d'];
  536. }
  537. if ($future['m'] != $past['m']) {
  538. $months --;
  539. }
  540. }
  541. if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) {
  542. $months = 11;
  543. $years --;
  544. }
  545. if ($months >= 12) {
  546. $years = $years + 1;
  547. $months = $months - 12;
  548. }
  549. if ($days >= 7) {
  550. $weeks = floor($days / 7);
  551. $days = $days - ($weeks * 7);
  552. }
  553. } else {
  554. $years = $months = $weeks = 0;
  555. $days = floor($diff / 86400);
  556. $diff = $diff - ($days * 86400);
  557. $hours = floor($diff / 3600);
  558. $diff = $diff - ($hours * 3600);
  559. $minutes = floor($diff / 60);
  560. $diff = $diff - ($minutes * 60);
  561. $seconds = $diff;
  562. }
  563. $relativeDate = '';
  564. $diff = $futureTime - $pastTime;
  565. if ($diff > abs($now - $this->fromString($end))) {
  566. $relativeDate = __d('cake', 'on %s', date($format, $inSeconds));
  567. } else {
  568. if ($years > 0) {
  569. // years and months and days
  570. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d year', '%d years', $years, $years);
  571. $relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months) : '';
  572. $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks) : '';
  573. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : '';
  574. } elseif (abs($months) > 0) {
  575. // months, weeks and days
  576. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d month', '%d months', $months, $months);
  577. $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks) : '';
  578. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : '';
  579. } elseif (abs($weeks) > 0) {
  580. // weeks and days
  581. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d week', '%d weeks', $weeks, $weeks);
  582. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days) : '';
  583. } elseif (abs($days) > 0) {
  584. // days and hours
  585. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d day', '%d days', $days, $days);
  586. $relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours) : '';
  587. } elseif (abs($hours) > 0) {
  588. // hours and minutes
  589. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d hour', '%d hours', $hours, $hours);
  590. $relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes) : '';
  591. } elseif (abs($minutes) > 0) {
  592. // minutes only
  593. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d minute', '%d minutes', $minutes, $minutes);
  594. } else {
  595. // seconds only
  596. $relativeDate .= ($relativeDate ? ', ' : '') . __dn('cake', '%d second', '%d seconds', $seconds, $seconds);
  597. }
  598. if (!$backwards) {
  599. $relativeDate = __d('cake', '%s ago', $relativeDate);
  600. }
  601. }
  602. return $relativeDate;
  603. }
  604. /**
  605. * Returns true if specified datetime was within the interval specified, else false.
  606. *
  607. * @param mixed $timeInterval the numeric value with space then time type.
  608. * Example of valid types: 6 hours, 2 days, 1 minute.
  609. * @param mixed $dateString the datestring or unix timestamp to compare
  610. * @param integer $userOffset User's offset from GMT (in hours)
  611. * @return boolean
  612. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#testing-time
  613. */
  614. public function wasWithinLast($timeInterval, $dateString, $userOffset = null) {
  615. $tmp = str_replace(' ', '', $timeInterval);
  616. if (is_numeric($tmp)) {
  617. $timeInterval = $tmp . ' ' . __d('cake', 'days');
  618. }
  619. $date = $this->fromString($dateString, $userOffset);
  620. $interval = $this->fromString('-' . $timeInterval);
  621. if ($date >= $interval && $date <= time()) {
  622. return true;
  623. }
  624. return false;
  625. }
  626. /**
  627. * Returns gmt as a UNIX timestamp.
  628. *
  629. * @param string $string UNIX timestamp or a valid strtotime() date string
  630. * @return integer UNIX timestamp
  631. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  632. */
  633. public function gmt($string = null) {
  634. if ($string != null) {
  635. $string = $this->fromString($string);
  636. } else {
  637. $string = time();
  638. }
  639. $hour = intval(date("G", $string));
  640. $minute = intval(date("i", $string));
  641. $second = intval(date("s", $string));
  642. $month = intval(date("n", $string));
  643. $day = intval(date("j", $string));
  644. $year = intval(date("Y", $string));
  645. return gmmktime($hour, $minute, $second, $month, $day, $year);
  646. }
  647. /**
  648. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  649. * This function also accepts a time string and a format string as first and second parameters.
  650. * In that case this function behaves as a wrapper for TimeHelper::i18nFormat()
  651. *
  652. * @param string $format date format string (or a DateTime string)
  653. * @param string $date Datetime string (or a date format string)
  654. * @param boolean $invalid flag to ignore results of fromString == false
  655. * @param integer $userOffset User's offset from GMT (in hours)
  656. * @return string Formatted date string
  657. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  658. */
  659. public function format($format, $date = null, $invalid = false, $userOffset = null) {
  660. $time = $this->fromString($date, $userOffset);
  661. $_time = $this->fromString($format, $userOffset);
  662. if (is_numeric($_time) && $time === false) {
  663. $format = $date;
  664. return $this->i18nFormat($_time, $format, $invalid, $userOffset);
  665. }
  666. if ($time === false && $invalid !== false) {
  667. return $invalid;
  668. }
  669. return date($format, $time);
  670. }
  671. /**
  672. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  673. * It take in account the default date format for the current language if a LC_TIME file is used.
  674. *
  675. * @param string $date Datetime string
  676. * @param string $format strftime format string.
  677. * @param boolean $invalid flag to ignore results of fromString == false
  678. * @param integer $userOffset User's offset from GMT (in hours)
  679. * @return string Formatted and translated date string
  680. * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#formatting
  681. */
  682. public function i18nFormat($date, $format = null, $invalid = false, $userOffset = null) {
  683. $date = $this->fromString($date, $userOffset);
  684. if ($date === false && $invalid !== false) {
  685. return $invalid;
  686. }
  687. if (empty($format)) {
  688. $format = '%x';
  689. }
  690. $format = $this->convertSpecifiers($format, $date);
  691. return $this->_strftime($format, $date);
  692. }
  693. /**
  694. * Multibyte wrapper for strftime.
  695. *
  696. * Handles utf8_encoding the result of strftime when necessary.
  697. *
  698. * @param string $format Format string.
  699. * @param int $date Timestamp to format.
  700. * @return string formatted string with correct encoding.
  701. */
  702. protected function _strftime($format, $date) {
  703. $format = strftime($format, $date);
  704. $encoding = Configure::read('App.encoding');
  705. if (!empty($encoding) && $encoding === 'UTF-8') {
  706. if (function_exists('mb_check_encoding')) {
  707. $valid = mb_check_encoding($format, $encoding);
  708. } else {
  709. $valid = !Multibyte::checkMultibyte($format);
  710. }
  711. if (!$valid) {
  712. $format = utf8_encode($format);
  713. }
  714. }
  715. return $format;
  716. }
  717. }