CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.10 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.10
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • None

Classes

  • CakeNumber
  • CakeText
  • CakeTime
  • ClassRegistry
  • Debugger
  • File
  • Folder
  • Hash
  • Inflector
  • ObjectCollection
  • Sanitize
  • Security
  • Set
  • String
  • Validation
  • Xml
   1: <?php
   2: /**
   3:  * CakeTime utility class file.
   4:  *
   5:  * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
   6:  * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  13:  * @link          https://cakephp.org CakePHP(tm) Project
  14:  * @package       Cake.Utility
  15:  * @since         CakePHP(tm) v 0.10.0.1076
  16:  * @license       https://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 https://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:                 static::${$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 static::${$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 https://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:         static::$_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', static::$_time)];
 155:                 }
 156:                 break;
 157:             case 'A':
 158:                 $day = __dc('cake', 'day', 5);
 159:                 if (is_array($day)) {
 160:                     return $day[date('w', static::$_time)];
 161:                 }
 162:                 break;
 163:             case 'c':
 164:                 $format = __dc('cake', 'd_t_fmt', 5);
 165:                 if ($format !== 'd_t_fmt') {
 166:                     return static::convertSpecifiers($format, static::$_time);
 167:                 }
 168:                 break;
 169:             case 'C':
 170:                 return sprintf("%02d", date('Y', static::$_time) / 100);
 171:             case 'D':
 172:                 return '%m/%d/%y';
 173:             case 'e':
 174:                 if (DS === '/') {
 175:                     return '%e';
 176:                 }
 177:                 $day = date('j', static::$_time);
 178:                 if ($day < 10) {
 179:                     $day = ' ' . $day;
 180:                 }
 181:                 return $day;
 182:             case 'eS' :
 183:                 return date('jS', static::$_time);
 184:             case 'b':
 185:             case 'h':
 186:                 $months = __dc('cake', 'abmon', 5);
 187:                 if (is_array($months)) {
 188:                     return $months[date('n', static::$_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', static::$_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', static::$_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', static::_translateSpecifier(array('%p', 'p')), $complete);
 213:                 }
 214:                 break;
 215:             case 'R':
 216:                 return date('H:i', static::$_time);
 217:             case 't':
 218:                 return "\t";
 219:             case 'T':
 220:                 return '%H:%M:%S';
 221:             case 'u':
 222:                 return ($weekDay = date('w', static::$_time)) ? $weekDay : 7;
 223:             case 'x':
 224:                 $format = __dc('cake', 'd_fmt', 5);
 225:                 if ($format !== 'd_fmt') {
 226:                     return static::convertSpecifiers($format, static::$_time);
 227:                 }
 228:                 break;
 229:             case 'X':
 230:                 $format = __dc('cake', 't_fmt', 5);
 231:                 if ($format !== 't_fmt') {
 232:                     return static::convertSpecifiers($format, static::$_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 int $serverTime Server's timestamp.
 243:  * @param string|DateTimeZone $timezone User's timezone string or DateTimeZone object.
 244:  * @return int User's timezone timestamp.
 245:  * @link https://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 = static::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 https://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 https://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 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 int|false Parsed given timezone timestamp.
 311:  * @link https://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 static::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 $date 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 https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::nice
 362:  */
 363:     public static function nice($date = null, $timezone = null, $format = null) {
 364:         if (!$date) {
 365:             $date = time();
 366:         }
 367:         $timestamp = static::fromString($date, $timezone);
 368:         if (!$format) {
 369:             $format = static::$niceFormat;
 370:         }
 371:         $convertedFormat = static::convertSpecifiers($format, $timestamp);
 372:         return static::_strftimeWithTimezone($convertedFormat, $timestamp, $date, $timezone);
 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 $date 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 https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::niceShort
 389:  */
 390:     public static function niceShort($date = null, $timezone = null) {
 391:         if (!$date) {
 392:             $date = time();
 393:         }
 394:         $timestamp = static::fromString($date, $timezone);
 395: 
 396:         if (static::isToday($date, $timezone)) {
 397:             $formattedDate = static::_strftimeWithTimezone("%H:%M", $timestamp, $date, $timezone);
 398:             return __d('cake', 'Today, %s', $formattedDate);
 399:         }
 400:         if (static::wasYesterday($date, $timezone)) {
 401:             $formattedDate = static::_strftimeWithTimezone("%H:%M", $timestamp, $date, $timezone);
 402:             return __d('cake', 'Yesterday, %s', $formattedDate);
 403:         }
 404:         if (static::isTomorrow($date, $timezone)) {
 405:             $formattedDate = static::_strftimeWithTimezone("%H:%M", $timestamp, $date, $timezone);
 406:             return __d('cake', 'Tomorrow, %s', $formattedDate);
 407:         }
 408: 
 409:         $d = static::_strftimeWithTimezone("%w", $timestamp, $date, $timezone);
 410:         $day = array(
 411:             __d('cake', 'Sunday'),
 412:             __d('cake', 'Monday'),
 413:             __d('cake', 'Tuesday'),
 414:             __d('cake', 'Wednesday'),
 415:             __d('cake', 'Thursday'),
 416:             __d('cake', 'Friday'),
 417:             __d('cake', 'Saturday')
 418:         );
 419:         if (static::wasWithinLast('7 days', $date, $timezone)) {
 420:             $formattedDate = static::_strftimeWithTimezone(static::$niceShortFormat, $timestamp, $date, $timezone);
 421:             return sprintf('%s %s', $day[$d], $formattedDate);
 422:         }
 423:         if (static::isWithinNext('7 days', $date, $timezone)) {
 424:             $formattedDate = static::_strftimeWithTimezone(static::$niceShortFormat, $timestamp, $date, $timezone);
 425:             return __d('cake', 'On %s %s', $day[$d], $formattedDate);
 426:         }
 427: 
 428:         $y = '';
 429:         if (!static::isThisYear($timestamp)) {
 430:             $y = ' %Y';
 431:         }
 432:         $format = static::convertSpecifiers("%b %eS{$y}, %H:%M", $timestamp);
 433:         return static::_strftimeWithTimezone($format, $timestamp, $date, $timezone);
 434:     }
 435: 
 436: /**
 437:  * Returns a partial SQL string to search for all records between two dates.
 438:  *
 439:  * @param int|string|DateTime $begin UNIX timestamp, strtotime() valid string or DateTime object
 440:  * @param int|string|DateTime $end UNIX timestamp, strtotime() valid string or DateTime object
 441:  * @param string $fieldName Name of database field to compare with
 442:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 443:  * @return string Partial SQL string.
 444:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::daysAsSql
 445:  */
 446:     public static function daysAsSql($begin, $end, $fieldName, $timezone = null) {
 447:         $begin = static::fromString($begin, $timezone);
 448:         $end = static::fromString($end, $timezone);
 449:         $begin = date('Y-m-d', $begin) . ' 00:00:00';
 450:         $end = date('Y-m-d', $end) . ' 23:59:59';
 451: 
 452:         return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
 453:     }
 454: 
 455: /**
 456:  * Returns a partial SQL string to search for all records between two times
 457:  * occurring on the same day.
 458:  *
 459:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 460:  * @param string $fieldName Name of database field to compare with
 461:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 462:  * @return string Partial SQL string.
 463:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::dayAsSql
 464:  */
 465:     public static function dayAsSql($dateString, $fieldName, $timezone = null) {
 466:         return static::daysAsSql($dateString, $dateString, $fieldName, $timezone);
 467:     }
 468: 
 469: /**
 470:  * Returns true if given datetime string is today.
 471:  *
 472:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 473:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 474:  * @return bool True if datetime string is today
 475:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isToday
 476:  */
 477:     public static function isToday($dateString, $timezone = null) {
 478:         $timestamp = static::fromString($dateString, $timezone);
 479:         $now = static::fromString('now', $timezone);
 480:         return date('Y-m-d', $timestamp) === date('Y-m-d', $now);
 481:     }
 482: 
 483: /**
 484:  * Returns true if given datetime string is in the future.
 485:  *
 486:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 487:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 488:  * @return bool True if datetime string is in the future
 489:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isFuture
 490:  */
 491:     public static function isFuture($dateString, $timezone = null) {
 492:         $timestamp = static::fromString($dateString, $timezone);
 493:         return $timestamp > time();
 494:     }
 495: 
 496: /**
 497:  * Returns true if given datetime string is in the past.
 498:  *
 499:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 500:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 501:  * @return bool True if datetime string is in the past
 502:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isPast
 503:  */
 504:     public static function isPast($dateString, $timezone = null) {
 505:         $timestamp = static::fromString($dateString, $timezone);
 506:         return $timestamp < time();
 507:     }
 508: 
 509: /**
 510:  * Returns true if given datetime string is within this week.
 511:  *
 512:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 513:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 514:  * @return bool True if datetime string is within current week
 515:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisWeek
 516:  */
 517:     public static function isThisWeek($dateString, $timezone = null) {
 518:         $timestamp = static::fromString($dateString, $timezone);
 519:         $now = static::fromString('now', $timezone);
 520:         return date('W o', $timestamp) === date('W o', $now);
 521:     }
 522: 
 523: /**
 524:  * Returns true if given datetime string is within this month
 525:  *
 526:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 527:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 528:  * @return bool True if datetime string is within current month
 529:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisMonth
 530:  */
 531:     public static function isThisMonth($dateString, $timezone = null) {
 532:         $timestamp = static::fromString($dateString, $timezone);
 533:         $now = static::fromString('now', $timezone);
 534:         return date('m Y', $timestamp) === date('m Y', $now);
 535:     }
 536: 
 537: /**
 538:  * Returns true if given datetime string is within current year.
 539:  *
 540:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 541:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 542:  * @return bool True if datetime string is within current year
 543:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isThisYear
 544:  */
 545:     public static function isThisYear($dateString, $timezone = null) {
 546:         $timestamp = static::fromString($dateString, $timezone);
 547:         $now = static::fromString('now', $timezone);
 548:         return date('Y', $timestamp) === date('Y', $now);
 549:     }
 550: 
 551: /**
 552:  * Returns true if given datetime string was yesterday.
 553:  *
 554:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 555:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 556:  * @return bool True if datetime string was yesterday
 557:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::wasYesterday
 558:  */
 559:     public static function wasYesterday($dateString, $timezone = null) {
 560:         $timestamp = static::fromString($dateString, $timezone);
 561:         $yesterday = static::fromString('yesterday', $timezone);
 562:         return date('Y-m-d', $timestamp) === date('Y-m-d', $yesterday);
 563:     }
 564: 
 565: /**
 566:  * Returns true if given datetime string is tomorrow.
 567:  *
 568:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 569:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 570:  * @return bool True if datetime string was yesterday
 571:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::isTomorrow
 572:  */
 573:     public static function isTomorrow($dateString, $timezone = null) {
 574:         $timestamp = static::fromString($dateString, $timezone);
 575:         $tomorrow = static::fromString('tomorrow', $timezone);
 576:         return date('Y-m-d', $timestamp) === date('Y-m-d', $tomorrow);
 577:     }
 578: 
 579: /**
 580:  * Returns the quarter
 581:  *
 582:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 583:  * @param bool $range if true returns a range in Y-m-d format
 584:  * @return int|array 1, 2, 3, or 4 quarter of year or array if $range true
 585:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toQuarter
 586:  */
 587:     public static function toQuarter($dateString, $range = false) {
 588:         $time = static::fromString($dateString);
 589:         $date = (int)ceil(date('m', $time) / 3);
 590:         if ($range === false) {
 591:             return $date;
 592:         }
 593: 
 594:         $year = date('Y', $time);
 595:         switch ($date) {
 596:             case 1:
 597:                 return array($year . '-01-01', $year . '-03-31');
 598:             case 2:
 599:                 return array($year . '-04-01', $year . '-06-30');
 600:             case 3:
 601:                 return array($year . '-07-01', $year . '-09-30');
 602:             case 4:
 603:                 return array($year . '-10-01', $year . '-12-31');
 604:         }
 605:     }
 606: 
 607: /**
 608:  * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
 609:  *
 610:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 611:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 612:  * @return int Unix timestamp
 613:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toUnix
 614:  */
 615:     public static function toUnix($dateString, $timezone = null) {
 616:         return static::fromString($dateString, $timezone);
 617:     }
 618: 
 619: /**
 620:  * Returns a formatted date in server's timezone.
 621:  *
 622:  * If a DateTime object is given or the dateString has a timezone
 623:  * segment, the timezone parameter will be ignored.
 624:  *
 625:  * If no timezone parameter is given and no DateTime object, the passed $dateString will be
 626:  * considered to be in the UTC timezone.
 627:  *
 628:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 629:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 630:  * @param string $format date format string
 631:  * @return mixed Formatted date
 632:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toServer
 633:  */
 634:     public static function toServer($dateString, $timezone = null, $format = 'Y-m-d H:i:s') {
 635:         if ($timezone === null) {
 636:             $timezone = new DateTimeZone('UTC');
 637:         } elseif (is_string($timezone)) {
 638:             $timezone = new DateTimeZone($timezone);
 639:         } elseif (!($timezone instanceof DateTimeZone)) {
 640:             return false;
 641:         }
 642: 
 643:         if ($dateString instanceof DateTime) {
 644:             $date = $dateString;
 645:         } elseif (is_int($dateString) || is_numeric($dateString)) {
 646:             $dateString = (int)$dateString;
 647: 
 648:             $date = new DateTime('@' . $dateString);
 649:             $date->setTimezone($timezone);
 650:         } else {
 651:             $date = new DateTime($dateString, $timezone);
 652:         }
 653: 
 654:         $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
 655:         return $date->format($format);
 656:     }
 657: 
 658: /**
 659:  * Returns a date formatted for Atom RSS feeds.
 660:  *
 661:  * @param string $dateString Datetime string or Unix timestamp
 662:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 663:  * @return string Formatted date string
 664:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toAtom
 665:  */
 666:     public static function toAtom($dateString, $timezone = null) {
 667:         return date('Y-m-d\TH:i:s\Z', static::fromString($dateString, $timezone));
 668:     }
 669: 
 670: /**
 671:  * Formats date for RSS feeds
 672:  *
 673:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 674:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 675:  * @return string Formatted date string
 676:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::toRSS
 677:  */
 678:     public static function toRSS($dateString, $timezone = null) {
 679:         $date = static::fromString($dateString, $timezone);
 680: 
 681:         if ($timezone === null) {
 682:             return date("r", $date);
 683:         }
 684: 
 685:         $userOffset = $timezone;
 686:         if (!is_numeric($timezone)) {
 687:             if (!is_object($timezone)) {
 688:                 $timezone = new DateTimeZone($timezone);
 689:             }
 690:             $currentDate = new DateTime('@' . $date);
 691:             $currentDate->setTimezone($timezone);
 692:             $userOffset = $timezone->getOffset($currentDate) / 60 / 60;
 693:         }
 694: 
 695:         $timezone = '+0000';
 696:         if ($userOffset != 0) {
 697:             $hours = (int)floor(abs($userOffset));
 698:             $minutes = (int)(fmod(abs($userOffset), $hours) * 60);
 699:             $timezone = ($userOffset < 0 ? '-' : '+') . str_pad($hours, 2, '0', STR_PAD_LEFT) . str_pad($minutes, 2, '0', STR_PAD_LEFT);
 700:         }
 701:         return date('D, d M Y H:i:s', $date) . ' ' . $timezone;
 702:     }
 703: 
 704: /**
 705:  * Returns either a relative or a formatted absolute date depending
 706:  * on the difference between the current time and given datetime.
 707:  * $datetime should be in a *strtotime* - parsable format, like MySQL's datetime datatype.
 708:  *
 709:  * ### Options:
 710:  *
 711:  * - `format` => a fall back format if the relative time is longer than the duration specified by end
 712:  * - `accuracy` => Specifies how accurate the date should be described (array)
 713:  *    - year =>   The format if years > 0   (default "day")
 714:  *    - month =>  The format if months > 0  (default "day")
 715:  *    - week =>   The format if weeks > 0   (default "day")
 716:  *    - day =>    The format if weeks > 0   (default "hour")
 717:  *    - hour =>   The format if hours > 0   (default "minute")
 718:  *    - minute => The format if minutes > 0 (default "minute")
 719:  *    - second => The format if seconds > 0 (default "second")
 720:  * - `end` => The end of relative time telling
 721:  * - `relativeString` => The printf compatible string when outputting past relative time
 722:  * - `relativeStringFuture` => The printf compatible string when outputting future relative time
 723:  * - `absoluteString` => The printf compatible string when outputting absolute time
 724:  * - `userOffset` => Users offset from GMT (in hours) *Deprecated* use timezone instead.
 725:  * - `timezone` => The user timezone the timestamp should be formatted in.
 726:  *
 727:  * Relative dates look something like this:
 728:  *
 729:  * - 3 weeks, 4 days ago
 730:  * - 15 seconds ago
 731:  *
 732:  * Default date formatting is d/m/yy e.g: on 18/2/09
 733:  *
 734:  * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
 735:  * like 'Posted ' before the function output.
 736:  *
 737:  * NOTE: If the difference is one week or more, the lowest level of accuracy is day
 738:  *
 739:  * @param int|string|DateTime $dateTime Datetime UNIX timestamp, strtotime() valid string or DateTime object
 740:  * @param array $options Default format if timestamp is used in $dateString
 741:  * @return string Relative time string.
 742:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::timeAgoInWords
 743:  */
 744:     public static function timeAgoInWords($dateTime, $options = array()) {
 745:         $timezone = null;
 746:         $accuracies = static::$wordAccuracy;
 747:         $format = static::$wordFormat;
 748:         $relativeEnd = static::$wordEnd;
 749:         $relativeStringPast = __d('cake', '%s ago');
 750:         $relativeStringFuture = __d('cake', 'in %s');
 751:         $absoluteString = __d('cake', 'on %s');
 752: 
 753:         if (is_string($options)) {
 754:             $format = $options;
 755:         } elseif (!empty($options)) {
 756:             if (isset($options['timezone'])) {
 757:                 $timezone = $options['timezone'];
 758:             } elseif (isset($options['userOffset'])) {
 759:                 $timezone = $options['userOffset'];
 760:             }
 761: 
 762:             if (isset($options['accuracy'])) {
 763:                 if (is_array($options['accuracy'])) {
 764:                     $accuracies = array_merge($accuracies, $options['accuracy']);
 765:                 } else {
 766:                     foreach ($accuracies as $key => $level) {
 767:                         $accuracies[$key] = $options['accuracy'];
 768:                     }
 769:                 }
 770:             }
 771: 
 772:             if (isset($options['format'])) {
 773:                 $format = $options['format'];
 774:             }
 775:             if (isset($options['end'])) {
 776:                 $relativeEnd = $options['end'];
 777:             }
 778:             if (isset($options['relativeString'])) {
 779:                 $relativeStringPast = $options['relativeString'];
 780:                 unset($options['relativeString']);
 781:             }
 782:             if (isset($options['relativeStringFuture'])) {
 783:                 $relativeStringFuture = $options['relativeStringFuture'];
 784:                 unset($options['relativeStringFuture']);
 785:             }
 786:             if (isset($options['absoluteString'])) {
 787:                 $absoluteString = $options['absoluteString'];
 788:                 unset($options['absoluteString']);
 789:             }
 790:             unset($options['end'], $options['format']);
 791:         }
 792: 
 793:         $now = static::fromString(time(), $timezone);
 794:         $inSeconds = static::fromString($dateTime, $timezone);
 795:         $isFuture = ($inSeconds > $now);
 796: 
 797:         if ($isFuture) {
 798:             $startTime = $now;
 799:             $endTime = $inSeconds;
 800:         } else {
 801:             $startTime = $inSeconds;
 802:             $endTime = $now;
 803:         }
 804:         $diff = $endTime - $startTime;
 805: 
 806:         if ($diff === 0) {
 807:             return __d('cake', 'just now', 'just now');
 808:         }
 809: 
 810:         $isAbsoluteDate = $diff > abs($now - static::fromString($relativeEnd));
 811:         if ($isAbsoluteDate) {
 812:             if (strpos($format, '%') === false) {
 813:                 $date = date($format, $inSeconds);
 814:             } else {
 815:                 $date = static::_strftime($format, $inSeconds);
 816:             }
 817:             return sprintf($absoluteString, $date);
 818:         }
 819: 
 820:         $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
 821: 
 822:         // If more than a week, then take into account the length of months
 823:         if ($diff >= 604800) {
 824:             list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $endTime));
 825:             list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $startTime));
 826: 
 827:             $years = $future['Y'] - $past['Y'];
 828:             $months = $future['m'] + ((12 * $years) - $past['m']);
 829: 
 830:             if ($months >= 12) {
 831:                 $years = floor($months / 12);
 832:                 $months = $months - ($years * 12);
 833:             }
 834:             if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] === 1) {
 835:                 $years--;
 836:             }
 837: 
 838:             if ($future['d'] >= $past['d']) {
 839:                 $days = $future['d'] - $past['d'];
 840:             } else {
 841:                 $daysInPastMonth = date('t', $startTime);
 842:                 $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
 843: 
 844:                 if ($isFuture) {
 845:                     $days = ($daysInFutureMonth - $past['d']) + $future['d'];
 846:                 } else {
 847:                     $days = ($daysInPastMonth - $past['d']) + $future['d'];
 848:                 }
 849: 
 850:                 if ($future['m'] != $past['m']) {
 851:                     $months--;
 852:                 }
 853:             }
 854: 
 855:             if (!$months && $years >= 1 && $diff < ($years * 31536000)) {
 856:                 $months = 11;
 857:                 $years--;
 858:             }
 859: 
 860:             if ($months >= 12) {
 861:                 $years = $years + 1;
 862:                 $months = $months - 12;
 863:             }
 864: 
 865:             if ($days >= 7) {
 866:                 $weeks = floor($days / 7);
 867:                 $days = $days - ($weeks * 7);
 868:             }
 869:         } else {
 870:             $days = floor($diff / 86400);
 871:             $diff = $diff - ($days * 86400);
 872: 
 873:             $hours = floor($diff / 3600);
 874:             $diff = $diff - ($hours * 3600);
 875: 
 876:             $minutes = floor($diff / 60);
 877:             $diff = $diff - ($minutes * 60);
 878: 
 879:             $seconds = $diff;
 880:         }
 881: 
 882:         $accuracy = $accuracies['second'];
 883:         if ($years > 0) {
 884:             $accuracy = $accuracies['year'];
 885:         } elseif (abs($months) > 0) {
 886:             $accuracy = $accuracies['month'];
 887:         } elseif (abs($weeks) > 0) {
 888:             $accuracy = $accuracies['week'];
 889:         } elseif (abs($days) > 0) {
 890:             $accuracy = $accuracies['day'];
 891:         } elseif (abs($hours) > 0) {
 892:             $accuracy = $accuracies['hour'];
 893:         } elseif (abs($minutes) > 0) {
 894:             $accuracy = $accuracies['minute'];
 895:         }
 896: 
 897:         $accuracyNum = str_replace(array('year', 'month', 'week', 'day', 'hour', 'minute', 'second'), array(1, 2, 3, 4, 5, 6, 7), $accuracy);
 898: 
 899:         $relativeDate = array();
 900:         if ($accuracyNum >= 1 && $years > 0) {
 901:             $relativeDate[] = __dn('cake', '%d year', '%d years', $years, $years);
 902:         }
 903:         if ($accuracyNum >= 2 && $months > 0) {
 904:             $relativeDate[] = __dn('cake', '%d month', '%d months', $months, $months);
 905:         }
 906:         if ($accuracyNum >= 3 && $weeks > 0) {
 907:             $relativeDate[] = __dn('cake', '%d week', '%d weeks', $weeks, $weeks);
 908:         }
 909:         if ($accuracyNum >= 4 && $days > 0) {
 910:             $relativeDate[] = __dn('cake', '%d day', '%d days', $days, $days);
 911:         }
 912:         if ($accuracyNum >= 5 && $hours > 0) {
 913:             $relativeDate[] = __dn('cake', '%d hour', '%d hours', $hours, $hours);
 914:         }
 915:         if ($accuracyNum >= 6 && $minutes > 0) {
 916:             $relativeDate[] = __dn('cake', '%d minute', '%d minutes', $minutes, $minutes);
 917:         }
 918:         if ($accuracyNum >= 7 && $seconds > 0) {
 919:             $relativeDate[] = __dn('cake', '%d second', '%d seconds', $seconds, $seconds);
 920:         }
 921:         $relativeDate = implode(', ', $relativeDate);
 922: 
 923:         if ($relativeDate) {
 924:             $relativeString = ($isFuture) ? $relativeStringFuture : $relativeStringPast;
 925:             return sprintf($relativeString, $relativeDate);
 926:         }
 927: 
 928:         if ($isFuture) {
 929:             $strings = array(
 930:                 'second' => __d('cake', 'in about a second'),
 931:                 'minute' => __d('cake', 'in about a minute'),
 932:                 'hour' => __d('cake', 'in about an hour'),
 933:                 'day' => __d('cake', 'in about a day'),
 934:                 'week' => __d('cake', 'in about a week'),
 935:                 'year' => __d('cake', 'in about a year')
 936:             );
 937:         } else {
 938:             $strings = array(
 939:                 'second' => __d('cake', 'about a second ago'),
 940:                 'minute' => __d('cake', 'about a minute ago'),
 941:                 'hour' => __d('cake', 'about an hour ago'),
 942:                 'day' => __d('cake', 'about a day ago'),
 943:                 'week' => __d('cake', 'about a week ago'),
 944:                 'year' => __d('cake', 'about a year ago')
 945:             );
 946:         }
 947: 
 948:         return $strings[$accuracy];
 949:     }
 950: 
 951: /**
 952:  * Returns true if specified datetime was within the interval specified, else false.
 953:  *
 954:  * @param string|int $timeInterval the numeric value with space then time type.
 955:  *    Example of valid types: 6 hours, 2 days, 1 minute.
 956:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 957:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 958:  * @return bool
 959:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::wasWithinLast
 960:  */
 961:     public static function wasWithinLast($timeInterval, $dateString, $timezone = null) {
 962:         $tmp = str_replace(' ', '', $timeInterval);
 963:         if (is_numeric($tmp)) {
 964:             $timeInterval = $tmp . ' ' . __d('cake', 'days');
 965:         }
 966: 
 967:         $date = static::fromString($dateString, $timezone);
 968:         $interval = static::fromString('-' . $timeInterval);
 969:         $now = static::fromString('now', $timezone);
 970: 
 971:         return $date >= $interval && $date <= $now;
 972:     }
 973: 
 974: /**
 975:  * Returns true if specified datetime is within the interval specified, else false.
 976:  *
 977:  * @param string|int $timeInterval the numeric value with space then time type.
 978:  *    Example of valid types: 6 hours, 2 days, 1 minute.
 979:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
 980:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
 981:  * @return bool
 982:  */
 983:     public static function isWithinNext($timeInterval, $dateString, $timezone = null) {
 984:         $tmp = str_replace(' ', '', $timeInterval);
 985:         if (is_numeric($tmp)) {
 986:             $timeInterval = $tmp . ' ' . __d('cake', 'days');
 987:         }
 988: 
 989:         $date = static::fromString($dateString, $timezone);
 990:         $interval = static::fromString('+' . $timeInterval);
 991:         $now = static::fromString('now', $timezone);
 992: 
 993:         return $date <= $interval && $date >= $now;
 994:     }
 995: 
 996: /**
 997:  * Returns gmt as a UNIX timestamp.
 998:  *
 999:  * @param int|string|DateTime $dateString UNIX timestamp, strtotime() valid string or DateTime object
1000:  * @return int UNIX timestamp
1001:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::gmt
1002:  */
1003:     public static function gmt($dateString = null) {
1004:         $time = time();
1005:         if ($dateString) {
1006:             $time = static::fromString($dateString);
1007:         }
1008:         return gmmktime(
1009:             (int)date('G', $time),
1010:             (int)date('i', $time),
1011:             (int)date('s', $time),
1012:             (int)date('n', $time),
1013:             (int)date('j', $time),
1014:             (int)date('Y', $time)
1015:         );
1016:     }
1017: 
1018: /**
1019:  * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
1020:  * This function also accepts a time string and a format string as first and second parameters.
1021:  * In that case this function behaves as a wrapper for TimeHelper::i18nFormat()
1022:  *
1023:  * ## Examples
1024:  *
1025:  * Create localized & formatted time:
1026:  *
1027:  * ```
1028:  *   CakeTime::format('2012-02-15', '%m-%d-%Y'); // returns 02-15-2012
1029:  *   CakeTime::format('2012-02-15 23:01:01', '%c'); // returns preferred date and time based on configured locale
1030:  *   CakeTime::format('0000-00-00', '%d-%m-%Y', 'N/A'); // return N/A becuase an invalid date was passed
1031:  *   CakeTime::format('2012-02-15 23:01:01', '%c', 'N/A', 'America/New_York'); // converts passed date to timezone
1032:  * ```
1033:  *
1034:  * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object (or a date format string)
1035:  * @param int|string|DateTime $format date format string (or UNIX timestamp, strtotime() valid string or DateTime object)
1036:  * @param bool|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
1037:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
1038:  * @return string Formatted date string
1039:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::format
1040:  * @see CakeTime::i18nFormat()
1041:  */
1042:     public static function format($date, $format = null, $default = false, $timezone = null) {
1043:         //Backwards compatible params re-order test
1044:         $time = static::fromString($format, $timezone);
1045: 
1046:         if ($time === false) {
1047:             return static::i18nFormat($date, $format, $default, $timezone);
1048:         }
1049:         return date($date, $time);
1050:     }
1051: 
1052: /**
1053:  * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
1054:  * It takes into account the default date format for the current language if a LC_TIME file is used.
1055:  *
1056:  * @param int|string|DateTime $date UNIX timestamp, strtotime() valid string or DateTime object
1057:  * @param string $format strftime format string.
1058:  * @param bool|string $default if an invalid date is passed it will output supplied default value. Pass false if you want raw conversion value
1059:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
1060:  * @return string Formatted and translated date string
1061:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::i18nFormat
1062:  */
1063:     public static function i18nFormat($date, $format = null, $default = false, $timezone = null) {
1064:         $timestamp = static::fromString($date, $timezone);
1065:         if ($timestamp === false && $default !== false) {
1066:             return $default;
1067:         }
1068:         if ($timestamp === false) {
1069:             return '';
1070:         }
1071:         if (empty($format)) {
1072:             $format = '%x';
1073:         }
1074:         $convertedFormat = static::convertSpecifiers($format, $timestamp);
1075:         return static::_strftimeWithTimezone($convertedFormat, $timestamp, $date, $timezone);
1076:     }
1077: 
1078: /**
1079:  * Get list of timezone identifiers
1080:  *
1081:  * @param int|string $filter A regex to filter identifier
1082:  *  Or one of DateTimeZone class constants (PHP 5.3 and above)
1083:  * @param string $country A two-letter ISO 3166-1 compatible country code.
1084:  *  This option is only used when $filter is set to DateTimeZone::PER_COUNTRY (available only in PHP 5.3 and above)
1085:  * @param bool|array $options If true (default value) groups the identifiers list by primary region.
1086:  *  Otherwise, an array containing `group`, `abbr`, `before`, and `after` keys.
1087:  *  Setting `group` and `abbr` to true will group results and append timezone
1088:  *  abbreviation in the display value. Set `before` and `after` to customize
1089:  *  the abbreviation wrapper.
1090:  * @return array List of timezone identifiers
1091:  * @since 2.2
1092:  * @link https://book.cakephp.org/2.0/en/core-libraries/helpers/time.html#TimeHelper::listTimezones
1093:  */
1094:     public static function listTimezones($filter = null, $country = null, $options = array()) {
1095:         if (is_bool($options)) {
1096:             $options = array(
1097:                 'group' => $options,
1098:             );
1099:         }
1100:         $defaults = array(
1101:             'group' => true,
1102:             'abbr' => false,
1103:             'before' => ' - ',
1104:             'after' => null,
1105:         );
1106:         $options += $defaults;
1107:         $group = $options['group'];
1108: 
1109:         $regex = null;
1110:         if (is_string($filter)) {
1111:             $regex = $filter;
1112:             $filter = null;
1113:         }
1114:         if (version_compare(PHP_VERSION, '5.3.0', '<')) {
1115:             if ($regex === null) {
1116:                 $regex = '#^((Africa|America|Antartica|Arctic|Asia|Atlantic|Australia|Europe|Indian|Pacific)/|UTC)#';
1117:             }
1118:             $identifiers = DateTimeZone::listIdentifiers();
1119:         } else {
1120:             if ($filter === null) {
1121:                 $filter = DateTimeZone::ALL;
1122:             }
1123:             $identifiers = DateTimeZone::listIdentifiers($filter, $country);
1124:         }
1125: 
1126:         if ($regex) {
1127:             foreach ($identifiers as $key => $tz) {
1128:                 if (!preg_match($regex, $tz)) {
1129:                     unset($identifiers[$key]);
1130:                 }
1131:             }
1132:         }
1133: 
1134:         if ($group) {
1135:             $return = array();
1136:             $now = time();
1137:             $before = $options['before'];
1138:             $after = $options['after'];
1139:             foreach ($identifiers as $key => $tz) {
1140:                 $abbr = null;
1141:                 if ($options['abbr']) {
1142:                     $dateTimeZone = new DateTimeZone($tz);
1143:                     $trans = $dateTimeZone->getTransitions($now, $now);
1144:                     $abbr = isset($trans[0]['abbr']) ?
1145:                         $before . $trans[0]['abbr'] . $after :
1146:                         null;
1147:                 }
1148:                 $item = explode('/', $tz, 2);
1149:                 if (isset($item[1])) {
1150:                     $return[$item[0]][$tz] = $item[1] . $abbr;
1151:                 } else {
1152:                     $return[$item[0]] = array($tz => $item[0] . $abbr);
1153:                 }
1154:             }
1155:             return $return;
1156:         }
1157:         return array_combine($identifiers, $identifiers);
1158:     }
1159: 
1160: /**
1161:  * Multibyte wrapper for strftime.
1162:  *
1163:  * Handles utf8_encoding the result of strftime when necessary.
1164:  *
1165:  * @param string $format Format string.
1166:  * @param int $timestamp Timestamp to format.
1167:  * @return string formatted string with correct encoding.
1168:  */
1169:     protected static function _strftime($format, $timestamp) {
1170:         $format = strftime($format, $timestamp);
1171:         $encoding = Configure::read('App.encoding');
1172:         if (!empty($encoding) && $encoding === 'UTF-8') {
1173:             if (function_exists('mb_check_encoding')) {
1174:                 $valid = mb_check_encoding($format, $encoding);
1175:             } else {
1176:                 $valid = Multibyte::checkMultibyte($format);
1177:             }
1178:             if (!$valid) {
1179:                 $format = utf8_encode($format);
1180:             }
1181:         }
1182:         return $format;
1183:     }
1184: 
1185: /**
1186:  * Multibyte wrapper for strftime.
1187:  *
1188:  * Adjusts the timezone when necessary before formatting the time.
1189:  *
1190:  * @param string $format Format string.
1191:  * @param int $timestamp Timestamp to format.
1192:  * @param int|string|DateTime $date Timestamp, strtotime() valid string or DateTime object.
1193:  * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object.
1194:  * @return string Formatted date string with correct encoding.
1195:  */
1196:     protected static function _strftimeWithTimezone($format, $timestamp, $date, $timezone) {
1197:         $serverTimeZone = date_default_timezone_get();
1198:         if (
1199:             !empty($timezone) &&
1200:             $date instanceof DateTime &&
1201:             $date->getTimezone()->getName() != $serverTimeZone
1202:         ) {
1203:             date_default_timezone_set($timezone);
1204:         }
1205:         $result = static::_strftime($format, $timestamp);
1206:         date_default_timezone_set($serverTimeZone);
1207:         return $result;
1208:     }
1209: 
1210: }
1211: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs