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