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
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <olivier.laviale@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\CLDR;
use ICanBoogie\Accessor\AccessorTrait;
/**
* Provides date and time localization.
*
* The class allows you to format dates and times in a locale-sensitive manner using
* {@link http://www.unicode.org/reports/tr35/#Date_Format_Patterns Unicode format patterns}.
*
* @property-read Calendar $calendar The calendar used by the formatter.
*/
class DateTimeFormatter implements Formatter
{
use AccessorTrait;
const WIDTH_FULL = 'full';
const WIDTH_LONG = 'long';
const WIDTH_MEDIUM = 'medium';
const WIDTH_SHORT = 'short';
static private $widths = [
self::WIDTH_FULL,
self::WIDTH_LONG,
self::WIDTH_MEDIUM,
self::WIDTH_SHORT,
];
/**
* Pattern characters mapping to the corresponding translator methods.
*
* @var array
*/
static protected $formatters = [
'G' => 'format_era',
'y' => 'format_year',
// 'Y' => Year (in "Week of Year" based calendars).
// 'u' => Extended year.
'Q' => 'format_quarter',
'q' => 'format_standalone_quarter',
'M' => 'format_month',
'L' => 'format_standalone_month',
// 'l' => Special symbol for Chinese leap month, used in combination with M. Only used with the Chinese calendar.
'w' => 'format_week_of_year',
'W' => 'format_week_of_month',
'd' => 'format_day_of_month',
'D' => 'format_day_of_year',
'F' => 'format_day_of_week_in_month',
'h' => 'format_hour12',
'H' => 'format_hour24',
'm' => 'format_minutes',
's' => 'format_seconds',
'E' => 'format_day_in_week',
'c' => 'format_day_in_week_stand_alone',
'e' => 'format_day_in_week_local',
'a' => 'format_period',
'k' => 'format_hour_in_day',
'K' => 'format_hour_in_period',
'z' => 'format_timezone_non_location',
'Z' => 'format_timezone_basic',
'v' => 'format_timezone_non_location'
];
/**
* Parses the datetime format pattern.
*
* @param string $pattern The pattern to be parsed.
*
* @return array Tokenized parsing result.
*/
static protected function tokenize($pattern)
{
static $formats = [];
if (isset($formats[$pattern]))
{
return $formats[$pattern];
}
$tokens = [];
$is_literal = false;
$literal = '';
for ($i = 0, $n = strlen($pattern) ; $i < $n ; ++$i)
{
$c = $pattern{$i};
if ($c === "'")
{
if ($i < $n-1 && $pattern{$i+1} === "'")
{
$tokens[] = "'";
$i++;
}
else if ($is_literal)
{
$tokens[] = $literal;
$literal = '';
$is_literal = false;
}
else
{
$is_literal = true;
$literal = '';
}
}
else if ($is_literal)
{
$literal .= $c;
}
else
{
for ($j = $i + 1 ; $j < $n ; ++$j)
{
if ($pattern{$j} !== $c) break;
}
$l = $j-$i;
$p = str_repeat($c, $l);
$tokens[] = isset(self::$formatters[$c]) ? [ self::$formatters[$c], $l ] : $p;
$i = $j - 1;
}
}
if ($literal)
{
$tokens[] = $literal;
}
return $formats[$pattern] = $tokens;
}
/**
* Pad a numeric value with zero on its left.
*
* @param int $value
* @param int $length
*
* @return string
*/
static private function numeric_pad($value, $length = 2)
{
return str_pad($value, $length, '0', STR_PAD_LEFT);
}
/**
* The calendar used to format the datetime.
*
* @var Calendar
*/
protected $calendar;
/**
* @return Calendar
*/
protected function get_calendar()
{
return $this->calendar;
}
/**
* Initializes the {@link $calendar} property.
*
* @param Calendar $calendar
*/
public function __construct(Calendar $calendar)
{
$this->calendar = $calendar;
}
/**
* Alias to the {@link format()} method.
*
* @param mixed $datetime
* @param string $pattern_or_width_or_skeleton
*
* @return string
*/
public function __invoke($datetime, $pattern_or_width_or_skeleton)
{
return $this->format($datetime, $pattern_or_width_or_skeleton);
}
/**
* Formats a date according to a pattern.
*
* @param \DateTimeInterface|string|int $datetime The datetime to format.
* @param string $pattern_or_width_or_skeleton The datetime can be formatted using a pattern,
* a width (WIDTH_*) or a skeleton. To format the datetime using a so-called "skeleton",
* the skeleton identifier must be prefixed with the colon sign ":" e.g. ":Ehm". The skeleton
* identifies the patterns defined under `availableFormats`.
*
* @return string The formatted date time.
*
* @see http://www.unicode.org/reports/tr35/#Date_Format_Patterns
*
* @uses format_era
* @uses format_year
* @uses format_standalone_quarter
* @uses format_standalone_month
* @uses format_week_of_year
* @uses format_week_of_month
* @uses format_day_of_month
* @uses format_day_of_year
* @uses format_day_of_week_in_month
* @uses format_day_in_week
* @uses format_day_in_week_stand_alone
* @uses format_day_in_week_local
* @uses format_period
* @uses format_hour12
* @uses format_hour24
* @uses format_hour_in_period
* @uses format_hour_in_day
* @uses format_minutes
* @uses format_seconds
* @uses format_timezone_basic
* @uses format_timezone_non_location
*/
public function format($datetime, $pattern_or_width_or_skeleton)
{
$datetime = $this->ensure_datetime($datetime);
$datetime = new DateTimeAccessor($datetime);
$pattern = $this->resolve_pattern($pattern_or_width_or_skeleton);
$tokens = self::tokenize($pattern);
$rc = '';
foreach ($tokens as $token)
{
if (is_array($token)) // a callback: method name, repeating chars
{
$token = $this->{ $token[0] }($datetime, $token[1]);
}
$rc .= $token;
}
return $rc;
}
/**
* Resolves the specified pattern, which can be a width, a skeleton or an actual pattern.
*
* @param string $pattern_or_width_or_skeleton
*
* @return string
*/
protected function resolve_pattern($pattern_or_width_or_skeleton)
{
$pattern = $pattern_or_width_or_skeleton;
if ($pattern_or_width_or_skeleton{0} === ':')
{
$skeleton = substr($pattern, 1);
$available_formats = $this->calendar['dateTimeFormats']['availableFormats'];
if (isset($available_formats[$skeleton]))
{
return $available_formats[$skeleton];
}
}
else if (in_array($pattern_or_width_or_skeleton, self::$widths))
{
$calendar = $this->calendar;
$width = $pattern_or_width_or_skeleton;
$datetime_pattern = $calendar['dateTimeFormats'][$width];
$date_pattern = $calendar['dateFormats'][$width];
$time_pattern = $calendar['timeFormats'][$width];
$pattern = strtr($datetime_pattern, [ '{1}' => $date_pattern, '{0}' => $time_pattern ]);
}
return $pattern;
}
/**
* Resolves widths (full, long, medium, short) into a pattern.
*
* @param string $pattern_or_width_or_skeleton
* @param string $from Width Source e.g. "timeFormats".
*
* @return string
*/
protected function resolve_width($pattern_or_width_or_skeleton, $from)
{
if (in_array($pattern_or_width_or_skeleton, self::$widths))
{
return $this->calendar[$from][$pattern_or_width_or_skeleton];
}
return $pattern_or_width_or_skeleton;
}
/*
* era (G)
*/
/**
* Era - Replaced with the Era string for the current date. One to three letters for the
* abbreviated form, four letters for the long form, five for the narrow form. [1..3,4,5]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string era
* @todo How to support multiple Eras?, e.g. Japanese.
*/
private function format_era(DateTimeAccessor $datetime, $length)
{
if ($length > 5)
{
return '';
}
$era = ($datetime->year > 0) ? 1 : 0;
switch($length)
{
case 1:
case 2:
case 3: return $this->calendar->abbreviated_eras[$era];
case 4: return $this->calendar->wide_eras[$era];
case 5: return $this->calendar->narrow_eras[$era];
}
return ''; // @codeCoverageIgnore
}
/*
* year (y)
*/
/**
* Year. Normally the length specifies the padding, but for two letters it also specifies the
* maximum length. [1..n]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string formatted year
*/
private function format_year(DateTimeAccessor $datetime, $length)
{
$year = $datetime->year;
if ($length == 2)
{
$year = $year % 100;
}
return self::numeric_pad($year, $length);
}
/*
* quarter (Q,q)
*/
/**
* Quarter - Use one or two "Q" for the numerical quarter, three for the abbreviation, or four
* for the full (wide) name. [1..2,3,4]
*
* @param DateTimeAccessor $datetime Datetime.
* @param int $length Number of repetition.
* @param string $abbreviated
* @param string $wide
*
* @return string
*/
private function format_quarter(
DateTimeAccessor $datetime,
$length,
$abbreviated = 'abbreviated_quarters',
$wide = 'wide_quarters'
) {
if ($length > 4)
{
return '';
}
$quarter = $datetime->quarter;
switch ($length)
{
case 1: return $quarter;
case 2: return self::numeric_pad($quarter);
case 3: $names = $this->calendar->$abbreviated; return $names[$quarter];
case 4: $names = $this->calendar->$wide; return $names[$quarter];
}
return ''; // @codeCoverageIgnore
}
/**
* Stand-Alone Quarter - Use one or two "q" for the numerical quarter, three for the
* abbreviation, or four for the full (wide) name. [1..2,3,4]
*
* @param DateTimeAccessor $datetime Datetime.
* @param int $length Number of repetition.
*
* @return string
*/
private function format_standalone_quarter(DateTimeAccessor $datetime, $length)
{
return $this->format_quarter(
$datetime,
$length,
'standalone_abbreviated_quarters',
'standalone_wide_quarters'
);
}
/*
* month (M|L)
*/
/**
* Month - Use one or two "M" for the numerical month, three for the abbreviation, four for
* the full name, or five for the narrow name. [1..2,3,4,5]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
* @param string $abbreviated
* @param string $wide
* @param string $narrow
*
* @return string
*/
private function format_month(
DateTimeAccessor $datetime,
$length,
$abbreviated = 'abbreviated_months',
$wide = 'wide_months',
$narrow = 'narrow_months'
) {
if ($length > 5)
{
return '';
}
$month = $datetime->month;
switch ($length)
{
case 1: return $month;
case 2: return self::numeric_pad($month);
case 3: $names = $this->calendar->$abbreviated; return $names[$month];
case 4: $names = $this->calendar->$wide; return $names[$month];
case 5: $names = $this->calendar->$narrow; return $names[$month];
}
return ''; // @codeCoverageIgnore
}
/**
* Stand-Alone Month - Use one or two "L" for the numerical month, three for the abbreviation,
* or four for the full (wide) name, or 5 for the narrow name. [1..2,3,4,5]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_standalone_month(DateTimeAccessor $datetime, $length)
{
return $this->format_month(
$datetime,
$length,
'standalone_abbreviated_months',
'standalone_wide_months',
'standalone_narrow_months'
);
}
/*
* week (w|W)
*/
/**
* Week of Year. [1..2]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_week_of_year(DateTimeAccessor $datetime, $length)
{
if ($length > 2)
{
return '';
}
$week = $datetime->week;
return $length == 1 ? $week : self::numeric_pad($week);
}
/**
* Week of Month. [1]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return int|false Week of month, of `false` if `$length` is greater than 1.
*/
private function format_week_of_month(DateTimeAccessor $datetime, $length)
{
if ($length > 1)
{
return '';
}
return ceil($datetime->day / 7);
}
/*
* day (d,D,F)
*/
/**
* Date - Day of the month. [1..2]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_day_of_month(DateTimeAccessor $datetime, $length)
{
if ($length > 2)
{
return '';
}
$day = $datetime->day;
if ($length == 1)
{
return $day;
}
return self::numeric_pad($day);
}
/**
* Day of year. [1..3]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_day_of_year(DateTimeAccessor $datetime, $length)
{
$day = $datetime->year_day;
if ($length > 3)
{
return '';
}
return self::numeric_pad($day, $length);
}
/**
* Day of Week in Month. The example is for the 2nd Wed in July. [1]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_day_of_week_in_month(DateTimeAccessor $datetime, $length)
{
if ($length > 1)
{
return '';
}
return floor(($datetime->day + 6) / 7);
}
/*
* weekday (E,e,c)
*/
/**
* Day of week - Use one through three letters for the short day, or four for the full name,
* five for the narrow name, or six for the short name. [1..3,4,5,6]
*
* @param DateTimeAccessor $datetime
* @param int $length
*
* @return string
*/
private function format_day_in_week(DateTimeAccessor $datetime, $length)
{
if ($length > 6)
{
return '';
}
$day = $datetime->weekday;
$code = $this->resolve_day_code($day);
$calendar = $this->calendar;
switch ($length)
{
case 1:
case 2:
case 3:
return $calendar->abbreviated_days[$code];
case 4:
return $calendar->wide_days[$code];
case 5:
return $calendar->narrow_days[$code];
case 6:
return $calendar->short_days[$code];
}
return ''; // @codeCoverageIgnore
}
/**
* Stand-Alone local day of week - Use one letter for the local numeric value (same as 'e'),
* three for the abbreviated day name, four for the full (wide) name, five for the narrow name,
* or six for the short name.
*
* @param DateTimeAccessor $datetime
* @param int $length
*
* @return string
*/
private function format_day_in_week_stand_alone(DateTimeAccessor $datetime, $length)
{
static $mapping = [
3 => 'abbreviated',
4 => 'wide',
5 => 'narrow',
6 => 'short',
];
if ($length == 2 || $length > 6)
{
return '';
}
$day = $datetime->weekday;
if ($length == 1)
{
return $day;
}
$code = $this->resolve_day_code($day);
return $this->calendar->{ 'standalone_' . $mapping[$length] . '_days' }[$code];
}
/**
* Local day of week. Same as E except adds a numeric value that will depend on the local
* starting day of the week, using one or two letters. For this example, Monday is the
* first day of the week.
*
* @param DateTimeAccessor $datetime
* @param int $length
*
* @return string
*/
private function format_day_in_week_local(DateTimeAccessor $datetime, $length)
{
if ($length < 3)
{
return $datetime->weekday;
}
return $this->format_day_in_week($datetime, $length);
}
/*
* period (a)
*/
/**
* AM or PM. [1]
*
* @param DateTimeAccessor $datetime
*
* @return string AM or PM designator
*/
private function format_period(DateTimeAccessor $datetime)
{
return $this->calendar['dayPeriods']['format']['abbreviated'][$datetime->hour < 12 ? 'am' : 'pm'];
}
/*
* hour (h,H,K,k)
*/
/**
* Hour [1-12]. When used in skeleton data or in a skeleton passed in an API for flexible data
* pattern generation, it should match the 12-hour-cycle format preferred by the locale
* (h or K); it should not match a 24-hour-cycle format (H or k). Use hh for zero
* padding. [1..2]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_hour12(DateTimeAccessor $datetime, $length)
{
if ($length > 2)
{
return '';
}
$hour = $datetime->hour;
$hour = ($hour == 12) ? 12 : $hour % 12;
if ($length == 1)
{
return $hour;
}
return self::numeric_pad($hour);
}
/**
* Hour [0-23]. When used in skeleton data or in a skeleton passed in an API for flexible
* data pattern generation, it should match the 24-hour-cycle format preferred by the
* locale (H or k); it should not match a 12-hour-cycle format (h or K). Use HH for zero
* padding. [1..2]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string
*/
private function format_hour24(DateTimeAccessor $datetime, $length)
{
if ($length > 2)
{
return '';
}
$hour = $datetime->hour;
if ($length == 1)
{
return $hour;
}
return self::numeric_pad($hour);
}
/**
* Hour [0-11]. When used in a skeleton, only matches K or h, see above. Use KK for zero
* padding. [1..2]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return integer hours in AM/PM format.
*/
private function format_hour_in_period(DateTimeAccessor $datetime, $length)
{
if ($length > 2)
{
return '';
}
$hour = $datetime->hour % 12;
if ($length == 1)
{
return $hour;
}
return self::numeric_pad($hour);
}
/**
* Hour [1-24]. When used in a skeleton, only matches k or H, see above. Use kk for zero
* padding. [1..2]
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return integer
*/
private function format_hour_in_day(DateTimeAccessor $datetime, $length)
{
if ($length > 2)
{
return '';
}
$hour = $datetime->hour ?: 24;
if ($length == 1)
{
return $hour;
}
return self::numeric_pad($hour);
}
/*
* minute (m)
*/
/**
* Minute. Use one or two "m" for zero padding.
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition
*
* @return string minutes.
*/
private function format_minutes(DateTimeAccessor $datetime, $length)
{
return $this->format_minutes_or_seconds($datetime, $length, 'minute');
}
/*
* second
*/
/**
* Second. Use one or two "s" for zero padding.
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition.
*
* @return string seconds
*/
private function format_seconds(DateTimeAccessor $datetime, $length)
{
return $this->format_minutes_or_seconds($datetime, $length, 'second');
}
/**
* Minute. Use one or two "m" for zero padding.
*
* @param DateTimeAccessor $datetime
* @param int $length Number of repetition
* @param string $which
*
* @return string minutes.
*/
private function format_minutes_or_seconds(DateTimeAccessor $datetime, $length, $which)
{
if ($length > 2)
{
return '';
}
$value = $datetime->$which;
if ($length == 1)
{
return $value;
}
return self::numeric_pad($value);
}
/*
* zone (z,Z,v)
*/
/**
* The ISO8601 basic format.
*
* @param DateTimeAccessor $datetime
*
* @return string
*/
private function format_timezone_basic(DateTimeAccessor $datetime)
{
return $datetime->format('O');
}
/**
* The specific non-location format.
*
* @param DateTimeAccessor $datetime
*
* @return string
*/
private function format_timezone_non_location(DateTimeAccessor $datetime)
{
$str = $datetime->format('T');
return $str === 'Z' ? 'UTC' : $str;
}
/**
* @param \DateTimeInterface|string|int $datetime
*
* @return \DateTimeInterface
*/
private function ensure_datetime($datetime)
{
if ($datetime instanceof \DateTimeInterface)
{
return $datetime;
}
return new \DateTime(is_numeric($datetime) ? "@$datetime" : (string) $datetime);
}
/**
* @param int $day
*
* @return string
*/
private function resolve_day_code($day)
{
static $translate = [
1 => 'mon',
2 => 'tue',
3 => 'wed',
4 => 'thu',
5 => 'fri',
6 => 'sat',
7 => 'sun'
];
return $translate[$day];
}
}