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