PageRenderTime 51ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/libs/view/helpers/time.php

https://github.com/msadouni/cakephp2x
PHP | 552 lines | 283 code | 54 blank | 215 comment | 67 complexity | f195524a68f09f5d21ca253cbd5b00b5 MD5 | raw file
  1. <?php
  2. /**
  3. * Time Helper class file.
  4. *
  5. * PHP Version 5.x
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2009, 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-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake
  16. * @subpackage cake.cake.libs.view.helpers
  17. * @since CakePHP(tm) v 0.10.0.1076
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. /**
  21. * Time Helper class for easy use of time data.
  22. *
  23. * Manipulation of time data.
  24. *
  25. * @package cake
  26. * @subpackage cake.cake.libs.view.helpers
  27. */
  28. class TimeHelper extends AppHelper {
  29. /**
  30. * Converts given time (in server's time zone) to user's local time, given his/her offset from GMT.
  31. *
  32. * @param string $serverTime UNIX timestamp
  33. * @param int $userOffset User's offset from GMT (in hours)
  34. * @return string UNIX timestamp
  35. */
  36. public function convert($serverTime, $userOffset) {
  37. $serverOffset = $this->serverOffset();
  38. $gmtTime = $serverTime - $serverOffset;
  39. $userTime = $gmtTime + $userOffset * (60*60);
  40. return $userTime;
  41. }
  42. /**
  43. * Returns server's offset from GMT in seconds.
  44. *
  45. * @return int Offset
  46. * @access public
  47. */
  48. public function serverOffset() {
  49. return date('Z', time());
  50. }
  51. /**
  52. * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
  53. *
  54. * @param string $dateString Datetime string
  55. * @param int $userOffset User's offset from GMT (in hours)
  56. * @return string Parsed timestamp
  57. * @access public
  58. */
  59. public function fromString($dateString, $userOffset = null) {
  60. if (empty($dateString)) {
  61. return false;
  62. }
  63. if (is_int($dateString) || is_numeric($dateString)) {
  64. $date = intval($dateString);
  65. } else {
  66. $date = strtotime($dateString);
  67. }
  68. if ($userOffset !== null) {
  69. return $this->convert($date, $userOffset);
  70. }
  71. return $date;
  72. }
  73. /**
  74. * Returns a nicely formatted date string for given Datetime string.
  75. *
  76. * @param string $dateString Datetime string or Unix timestamp
  77. * @param int $userOffset User's offset from GMT (in hours)
  78. * @return string Formatted date string
  79. * @access public
  80. */
  81. public function nice($dateString = null, $userOffset = null) {
  82. if ($dateString != null) {
  83. $date = $this->fromString($dateString, $userOffset);
  84. } else {
  85. $date = time();
  86. }
  87. return date("D, M jS Y, H:i", $date);
  88. }
  89. /**
  90. * Returns a formatted descriptive date string for given datetime string.
  91. *
  92. * If the given date is today, the returned string could be "Today, 16:54".
  93. * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
  94. * If $dateString's year is the current year, the returned string does not
  95. * include mention of the year.
  96. *
  97. * @param string $dateString Datetime string or Unix timestamp
  98. * @param int $userOffset User's offset from GMT (in hours)
  99. * @return string Described, relative date string
  100. */
  101. public function niceShort($dateString = null, $userOffset = null) {
  102. $date = $dateString ? $this->fromString($dateString, $userOffset) : time();
  103. $y = $this->isThisYear($date) ? '' : ' Y';
  104. if ($this->isToday($date)) {
  105. $ret = sprintf(__('Today, %s',true), date("H:i", $date));
  106. } elseif ($this->wasYesterday($date)) {
  107. $ret = sprintf(__('Yesterday, %s',true), date("H:i", $date));
  108. } else {
  109. $ret = date("M jS{$y}, H:i", $date);
  110. }
  111. return $ret;
  112. }
  113. /**
  114. * Returns a partial SQL string to search for all records between two dates.
  115. *
  116. * @param string $dateString Datetime string or Unix timestamp
  117. * @param string $end Datetime string or Unix timestamp
  118. * @param string $fieldName Name of database field to compare with
  119. * @param int $userOffset User's offset from GMT (in hours)
  120. * @return string Partial SQL string.
  121. */
  122. public function daysAsSql($begin, $end, $fieldName, $userOffset = null) {
  123. $begin = $this->fromString($begin, $userOffset);
  124. $end = $this->fromString($end, $userOffset);
  125. $begin = date('Y-m-d', $begin) . ' 00:00:00';
  126. $end = date('Y-m-d', $end) . ' 23:59:59';
  127. return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
  128. }
  129. /**
  130. * Returns a partial SQL string to search for all records between two times
  131. * occurring on the same day.
  132. *
  133. * @param string $dateString Datetime string or Unix timestamp
  134. * @param string $fieldName Name of database field to compare with
  135. * @param int $userOffset User's offset from GMT (in hours)
  136. * @return string Partial SQL string.
  137. */
  138. public function dayAsSql($dateString, $fieldName, $userOffset = null) {
  139. $date = $this->fromString($dateString, $userOffset);
  140. return $this->daysAsSql($dateString, $dateString, $fieldName);
  141. }
  142. /**
  143. * Returns true if given datetime string is today.
  144. *
  145. * @param string $dateString Datetime string or Unix timestamp
  146. * @param int $userOffset User's offset from GMT (in hours)
  147. * @return boolean True if datetime string is today
  148. */
  149. public function isToday($dateString, $userOffset = null) {
  150. $date = $this->fromString($dateString, $userOffset);
  151. return date('Y-m-d', $date) == date('Y-m-d', time());
  152. }
  153. /**
  154. * Returns true if given datetime string is within this week
  155. * @param string $dateString
  156. * @param int $userOffset User's offset from GMT (in hours)
  157. * @return boolean True if datetime string is within current week
  158. */
  159. public function isThisWeek($dateString, $userOffset = null) {
  160. $date = $this->fromString($dateString, $userOffset);
  161. return date('W Y', $date) == date('W Y', time());
  162. }
  163. /**
  164. * Returns true if given datetime string is within this month
  165. * @param string $dateString
  166. * @param int $userOffset User's offset from GMT (in hours)
  167. * @return boolean True if datetime string is within current month
  168. */
  169. public function isThisMonth($dateString, $userOffset = null) {
  170. $date = $this->fromString($dateString);
  171. return date('m Y',$date) == date('m Y', time());
  172. }
  173. /**
  174. * Returns true if given datetime string is within current year.
  175. *
  176. * @param string $dateString Datetime string or Unix timestamp
  177. * @return boolean True if datetime string is within current year
  178. */
  179. public function isThisYear($dateString, $userOffset = null) {
  180. $date = $this->fromString($dateString, $userOffset);
  181. return date('Y', $date) == date('Y', time());
  182. }
  183. /**
  184. * Returns true if given datetime string was yesterday.
  185. *
  186. * @param string $dateString Datetime string or Unix timestamp
  187. * @param int $userOffset User's offset from GMT (in hours)
  188. * @return boolean True if datetime string was yesterday
  189. */
  190. public function wasYesterday($dateString, $userOffset = null) {
  191. $date = $this->fromString($dateString, $userOffset);
  192. return date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday'));
  193. }
  194. /**
  195. * Returns true if given datetime string is tomorrow.
  196. *
  197. * @param string $dateString Datetime string or Unix timestamp
  198. * @param int $userOffset User's offset from GMT (in hours)
  199. * @return boolean True if datetime string was yesterday
  200. */
  201. public function isTomorrow($dateString, $userOffset = null) {
  202. $date = $this->fromString($dateString, $userOffset);
  203. return date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow'));
  204. }
  205. /**
  206. * Returns the quart
  207. * @param string $dateString
  208. * @param boolean $range if true returns a range in Y-m-d format
  209. * @return boolean True if datetime string is within current week
  210. */
  211. public function toQuarter($dateString, $range = false) {
  212. $time = $this->fromString($dateString);
  213. $date = ceil(date('m', $time) / 3);
  214. if ($range === true) {
  215. $range = 'Y-m-d';
  216. }
  217. if ($range !== false) {
  218. $year = date('Y', $time);
  219. switch ($date) {
  220. case 1:
  221. $date = array($year.'-01-01', $year.'-03-31');
  222. break;
  223. case 2:
  224. $date = array($year.'-04-01', $year.'-06-30');
  225. break;
  226. case 3:
  227. $date = array($year.'-07-01', $year.'-09-30');
  228. break;
  229. case 4:
  230. $date = array($year.'-10-01', $year.'-12-31');
  231. break;
  232. }
  233. }
  234. return $date;
  235. }
  236. /**
  237. * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
  238. *
  239. * @param string $dateString Datetime string to be represented as a Unix timestamp
  240. * @param int $userOffset User's offset from GMT (in hours)
  241. * @return integer Unix timestamp
  242. */
  243. public function toUnix($dateString, $userOffset = null) {
  244. return $this->fromString($dateString, $userOffset);
  245. }
  246. /**
  247. * Returns a date formatted for Atom RSS feeds.
  248. *
  249. * @param string $dateString Datetime string or Unix timestamp
  250. * @param int $userOffset User's offset from GMT (in hours)
  251. * @return string Formatted date string
  252. */
  253. public function toAtom($dateString, $userOffset = null) {
  254. $date = $this->fromString($dateString, $userOffset);
  255. return date('Y-m-d\TH:i:s\Z', $date);
  256. }
  257. /**
  258. * Formats date for RSS feeds
  259. *
  260. * @param string $dateString Datetime string or Unix timestamp
  261. * @param int $userOffset User's offset from GMT (in hours)
  262. * @return string Formatted date string
  263. */
  264. public function toRSS($dateString, $userOffset = null) {
  265. $date = $this->fromString($dateString, $userOffset);
  266. return date("r", $date);
  267. }
  268. /**
  269. * Returns either a relative date or a formatted date depending
  270. * on the difference between the current time and given datetime.
  271. * $datetime should be in a <i>strtotime</i> - parsable format, like MySQL's datetime datatype.
  272. *
  273. * Options:
  274. *
  275. * - 'format' => a fall back format if the relative time is longer than the duration specified by end
  276. * - 'end' => The end of relative time telling
  277. * - 'userOffset' => Users offset from GMT (in hours)
  278. *
  279. * Relative dates look something like this:
  280. * 3 weeks, 4 days ago
  281. * 15 seconds ago
  282. *
  283. * Default date formatting is d/m/yy e.g: on 18/2/09
  284. *
  285. * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
  286. * like 'Posted ' before the function output.
  287. *
  288. * @param string $dateString Datetime string or Unix timestamp
  289. * @param array $options Default format if timestamp is used in $dateString
  290. * @return string Relative time string.
  291. */
  292. public function timeAgoInWords($dateTime, $options = array()) {
  293. $userOffset = null;
  294. if (is_array($options) && isset($options['userOffset'])) {
  295. $userOffset = $options['userOffset'];
  296. }
  297. $now = time();
  298. if (!is_null($userOffset)) {
  299. $now = $this->convert(time(), $userOffset);
  300. }
  301. $inSeconds = $this->fromString($dateTime, $userOffset);
  302. $backwards = ($inSeconds > $now);
  303. $format = 'j/n/y';
  304. $end = '+1 month';
  305. if (is_array($options)) {
  306. if (isset($options['format'])) {
  307. $format = $options['format'];
  308. unset($options['format']);
  309. }
  310. if (isset($options['end'])) {
  311. $end = $options['end'];
  312. unset($options['end']);
  313. }
  314. } else {
  315. $format = $options;
  316. }
  317. if ($backwards) {
  318. $futureTime = $inSeconds;
  319. $pastTime = $now;
  320. } else {
  321. $futureTime = $now;
  322. $pastTime = $inSeconds;
  323. }
  324. $diff = $futureTime - $pastTime;
  325. // If more than a week, then take into account the length of months
  326. if ($diff >= 604800) {
  327. $current = array();
  328. $date = array();
  329. list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime));
  330. list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime));
  331. $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
  332. if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) {
  333. $months = 0;
  334. $years = 0;
  335. } else {
  336. if ($future['Y'] == $past['Y']) {
  337. $months = $future['m'] - $past['m'];
  338. } else {
  339. $years = $future['Y'] - $past['Y'];
  340. $months = $future['m'] + ((12 * $years) - $past['m']);
  341. if ($months >= 12) {
  342. $years = floor($months / 12);
  343. $months = $months - ($years * 12);
  344. }
  345. if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) {
  346. $years --;
  347. }
  348. }
  349. }
  350. if ($future['d'] >= $past['d']) {
  351. $days = $future['d'] - $past['d'];
  352. } else {
  353. $daysInPastMonth = date('t', $pastTime);
  354. $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
  355. if (!$backwards) {
  356. $days = ($daysInPastMonth - $past['d']) + $future['d'];
  357. } else {
  358. $days = ($daysInFutureMonth - $past['d']) + $future['d'];
  359. }
  360. if ($future['m'] != $past['m']) {
  361. $months --;
  362. }
  363. }
  364. if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) {
  365. $months = 11;
  366. $years --;
  367. }
  368. if ($months >= 12) {
  369. $years = $years + 1;
  370. $months = $months - 12;
  371. }
  372. if ($days >= 7) {
  373. $weeks = floor($days / 7);
  374. $days = $days - ($weeks * 7);
  375. }
  376. } else {
  377. $years = $months = $weeks = 0;
  378. $days = floor($diff / 86400);
  379. $diff = $diff - ($days * 86400);
  380. $hours = floor($diff / 3600);
  381. $diff = $diff - ($hours * 3600);
  382. $minutes = floor($diff / 60);
  383. $diff = $diff - ($minutes * 60);
  384. $seconds = $diff;
  385. }
  386. $relativeDate = '';
  387. $diff = $futureTime - $pastTime;
  388. if ($diff > abs($now - $this->fromString($end))) {
  389. $relativeDate = sprintf(__('on %s',true), date($format, $inSeconds));
  390. } else {
  391. if ($years > 0) {
  392. // years and months and days
  393. $relativeDate .= ($relativeDate ? ', ' : '') . $years . ' ' . __n('year', 'years', $years, true);
  394. $relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months, true) : '';
  395. $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true) : '';
  396. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
  397. } elseif (abs($months) > 0) {
  398. // months, weeks and days
  399. $relativeDate .= ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months, true);
  400. $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true) : '';
  401. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
  402. } elseif (abs($weeks) > 0) {
  403. // weeks and days
  404. $relativeDate .= ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks, true);
  405. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true) : '';
  406. } elseif (abs($days) > 0) {
  407. // days and hours
  408. $relativeDate .= ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days, true);
  409. $relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours, true) : '';
  410. } elseif (abs($hours) > 0) {
  411. // hours and minutes
  412. $relativeDate .= ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours, true);
  413. $relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes, true) : '';
  414. } elseif (abs($minutes) > 0) {
  415. // minutes only
  416. $relativeDate .= ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes, true);
  417. } else {
  418. // seconds only
  419. $relativeDate .= ($relativeDate ? ', ' : '') . $seconds . ' ' . __n('second', 'seconds', $seconds, true);
  420. }
  421. if (!$backwards) {
  422. $relativeDate = sprintf(__('%s ago', true), $relativeDate);
  423. }
  424. }
  425. return $relativeDate;
  426. }
  427. /**
  428. * Alias for timeAgoInWords
  429. *
  430. * @param mixed $dateTime Datetime string (strtotime-compatible) or Unix timestamp
  431. * @param mixed $options Default format string, if timestamp is used in $dateTime, or an array of options to be passed
  432. * on to timeAgoInWords().
  433. * @return string Relative time string.
  434. * @see TimeHelper::timeAgoInWords
  435. */
  436. public function relativeTime($dateTime, $options = array()) {
  437. return $this->timeAgoInWords($dateTime, $options);
  438. }
  439. /**
  440. * Returns true if specified datetime was within the interval specified, else false.
  441. *
  442. * @param mixed $timeInterval the numeric value with space then time type. Example of valid types: 6 hours, 2 days, 1 minute.
  443. * @param mixed $dateString the datestring or unix timestamp to compare
  444. * @param int $userOffset User's offset from GMT (in hours)
  445. * @return bool
  446. */
  447. public function wasWithinLast($timeInterval, $dateString, $userOffset = null) {
  448. $tmp = str_replace(' ', '', $timeInterval);
  449. if (is_numeric($tmp)) {
  450. $timeInterval = $tmp . ' ' . __('days', true);
  451. }
  452. $date = $this->fromString($dateString, $userOffset);
  453. $interval = $this->fromString('-'.$timeInterval);
  454. if ($date >= $interval && $date <= time()) {
  455. return true;
  456. }
  457. return false;
  458. }
  459. /**
  460. * Returns gmt, given either a UNIX timestamp or a valid strtotime() date string.
  461. *
  462. * @param string $dateString Datetime string
  463. * @return string Formatted date string
  464. */
  465. public function gmt($string = null) {
  466. if ($string != null) {
  467. $string = $this->fromString($string);
  468. } else {
  469. $string = time();
  470. }
  471. $string = $this->fromString($string);
  472. $hour = intval(date("G", $string));
  473. $minute = intval(date("i", $string));
  474. $second = intval(date("s", $string));
  475. $month = intval(date("n", $string));
  476. $day = intval(date("j", $string));
  477. $year = intval(date("Y", $string));
  478. $return = gmmktime($hour, $minute, $second, $month, $day, $year);
  479. return $return;
  480. }
  481. /**
  482. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  483. *
  484. * @param string $format date format string. defaults to 'd-m-Y'
  485. * @param string $dateString Datetime string
  486. * @param boolean $invalid flag to ignore results of fromString == false
  487. * @param int $userOffset User's offset from GMT (in hours)
  488. * @return string Formatted date string
  489. */
  490. public function format($format = 'd-m-Y', $date, $invalid = false, $userOffset = null) {
  491. $date = $this->fromString($date, $userOffset);
  492. if ($date === false && $invalid !== false) {
  493. return $invalid;
  494. }
  495. return date($format, $date);
  496. }
  497. }
  498. ?>