PageRenderTime 51ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/i18n/sfDateFormat.class.php

https://github.com/morhekil/symfony
PHP | 798 lines | 487 code | 65 blank | 246 comment | 79 complexity | 503729cc08d10a63c4acc495ac0d9fad MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, BSD-3-Clause
  1. <?php
  2. /**
  3. * sfDateFormat class file.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the BSD License.
  7. *
  8. * Copyright(c) 2004 by Qiang Xue. All rights reserved.
  9. *
  10. * To contact the author write to {@link mailto:qiang.xue@gmail.com Qiang Xue}
  11. * The latest version of PRADO can be obtained from:
  12. * {@link http://prado.sourceforge.net/}
  13. *
  14. * @author Wei Zhuo <weizhuo[at]gmail[dot]com>
  15. * @version $Id$
  16. * @package symfony
  17. * @subpackage i18n
  18. */
  19. /**
  20. * Get the encoding utilities
  21. */
  22. require_once(dirname(__FILE__).'/util.php');
  23. /**
  24. * sfDateFormat class.
  25. *
  26. * The sfDateFormat class allows you to format dates and times with
  27. * predefined styles in a locale-sensitive manner. Formatting times
  28. * with the sfDateFormat class is similar to formatting dates.
  29. *
  30. * Formatting dates with the sfDateFormat class is a two-step process.
  31. * First, you create a formatter with the getDateInstance method.
  32. * Second, you invoke the format method, which returns a string containing
  33. * the formatted date.
  34. *
  35. * DateTime values are formatted using standard or custom patterns stored
  36. * in the properties of a DateTimeFormatInfo.
  37. *
  38. * @author Xiang Wei Zhuo <weizhuo[at]gmail[dot]com>
  39. * @version v1.0, last update on Sat Dec 04 14:10:49 EST 2004
  40. * @package System.I18N.core
  41. */
  42. class sfDateFormat
  43. {
  44. /**
  45. * A list of tokens and their function call.
  46. * @var array
  47. */
  48. protected $tokens = array(
  49. 'G'=>'Era',
  50. 'y'=>'year',
  51. 'M'=>'mon',
  52. 'd'=>'mday',
  53. 'h'=>'Hour12',
  54. 'H'=>'hours',
  55. 'm'=>'minutes',
  56. 's'=>'seconds',
  57. 'E'=>'wday',
  58. 'D'=>'yday',
  59. 'F'=>'DayInMonth',
  60. 'w'=>'WeekInYear',
  61. 'W'=>'WeekInMonth',
  62. 'a'=>'AMPM',
  63. 'k'=>'HourInDay',
  64. 'K'=>'HourInAMPM',
  65. 'z'=>'TimeZone'
  66. );
  67. /**
  68. * A list of methods, to be used by the token function calls.
  69. * @var array
  70. */
  71. protected $methods = array();
  72. /**
  73. * The sfDateTimeFormatInfo, containing culture specific patterns and names.
  74. * @var sfDateTimeFormatInfo
  75. */
  76. protected $formatInfo;
  77. /**
  78. * Initialize a new sfDateFormat.
  79. *
  80. * @param mixed either, null, a sfCultureInfo instance, a DateTimeFormatInfo instance, or a locale.
  81. * @return sfDateFormat instance
  82. */
  83. function __construct($formatInfo = null)
  84. {
  85. if (is_null($formatInfo))
  86. {
  87. $this->formatInfo = sfDateTimeFormatInfo::getInvariantInfo();
  88. }
  89. else if ($formatInfo instanceof sfCultureInfo)
  90. {
  91. $this->formatInfo = $formatInfo->DateTimeFormat;
  92. }
  93. else if ($formatInfo instanceof sfDateTimeFormatInfo)
  94. {
  95. $this->formatInfo = $formatInfo;
  96. }
  97. else
  98. {
  99. $this->formatInfo = sfDateTimeFormatInfo::getInstance($formatInfo);
  100. }
  101. $this->methods = get_class_methods($this);
  102. }
  103. /**
  104. * Guesses a date without calling strtotime.
  105. *
  106. * @author Olivier Verdier <Olivier.Verdier@gmail.com>
  107. * @param mixed the time as integer or string in strtotime format.
  108. * @param string the input pattern; default is sql date or timestamp
  109. * @return array same array as the getdate function
  110. */
  111. public function getDate($time, $pattern = null)
  112. {
  113. if (is_null($time))
  114. {
  115. return null;
  116. }
  117. // if the type is not a php timestamp
  118. $isString = (string) $time !== (string) (int) $time;
  119. if ($isString)
  120. {
  121. if (!$pattern)
  122. {
  123. if (strlen($time) == 10)
  124. {
  125. $pattern = 'i';
  126. }
  127. else // otherwise, default:
  128. {
  129. $pattern = 'I';
  130. }
  131. }
  132. $pattern = $this->getPattern($pattern);
  133. $tokens = $this->getTokens($pattern);
  134. $pregPattern = '';
  135. $matchNames = array();
  136. foreach ($tokens as $token)
  137. {
  138. if ($matchName = $this->getFunctionName($token))
  139. {
  140. $pregPattern .= '(\d+)';
  141. $matchNames[] = $matchName;
  142. }
  143. else
  144. {
  145. $pregPattern .= '[^\d]+';
  146. }
  147. }
  148. preg_match('@'.$pregPattern.'@', $time, $matches);
  149. array_shift($matches);
  150. if (count($matchNames) == count($matches))
  151. {
  152. $date = array_combine($matchNames, $matches);
  153. // guess the date if input with two digits
  154. if (strlen($date['year']) == 2)
  155. {
  156. $date['year'] = date('Y', mktime(0, 0, 0, 1, 1, $date['year']));
  157. }
  158. $date = array_map('intval', $date);
  159. }
  160. }
  161. // the last attempt has failed we fall back on the default method
  162. if (!isset($date))
  163. {
  164. if ($isString)
  165. {
  166. $numericalTime = @strtotime($time);
  167. if ($numericalTime === false)
  168. {
  169. throw new sfException(sprintf('Impossible to parse date "%s" with format "%s"', $time, $pattern));
  170. }
  171. }
  172. else
  173. {
  174. $numericalTime = $time;
  175. }
  176. $date = @getdate($numericalTime);
  177. }
  178. // we set default values for the time
  179. foreach (array('hours', 'minutes', 'seconds') as $timeDiv)
  180. {
  181. if (!isset($date[$timeDiv]))
  182. {
  183. $date[$timeDiv] = 0;
  184. }
  185. }
  186. return $date;
  187. }
  188. /**
  189. * Format a date according to the pattern.
  190. *
  191. * @param mixed the time as integer or string in strtotime format.
  192. * @return string formatted date time.
  193. */
  194. public function format($time, $pattern = 'F', $inputPattern = null, $charset = 'UTF-8')
  195. {
  196. $date = $this->getDate($time, $inputPattern);
  197. if (is_null($pattern))
  198. {
  199. $pattern = 'F';
  200. }
  201. $pattern = $this->getPattern($pattern);
  202. $tokens = $this->getTokens($pattern);
  203. for ($i = 0, $max = count($tokens); $i < $max; $i++)
  204. {
  205. $pattern = $tokens[$i];
  206. if ($pattern{0} == "'" && $pattern{strlen($pattern) - 1} == "'")
  207. {
  208. $tokens[$i] = str_replace('``````', '\'', preg_replace('/(^\')|(\'$)/', '', $pattern));
  209. }
  210. else if ($pattern == '``````')
  211. {
  212. $tokens[$i] = '\'';
  213. }
  214. else
  215. {
  216. $function = ucfirst($this->getFunctionName($pattern));
  217. if ($function != null)
  218. {
  219. $fName = 'get'.$function;
  220. if (in_array($fName, $this->methods))
  221. {
  222. $tokens[$i] = $this->$fName($date, $pattern);
  223. }
  224. else
  225. {
  226. throw new sfException('function '.$function.' not found.');
  227. }
  228. }
  229. }
  230. }
  231. return I18N_toEncoding(implode('', $tokens), $charset);
  232. }
  233. /**
  234. * For a particular token, get the corresponding function to call.
  235. *
  236. * @param string token
  237. * @return mixed the function if good token, null otherwise.
  238. */
  239. protected function getFunctionName($token)
  240. {
  241. if (isset($this->tokens[$token{0}]))
  242. {
  243. return $this->tokens[$token{0}];
  244. }
  245. }
  246. /**
  247. * Get the pattern from DateTimeFormatInfo or some predefined patterns.
  248. * If the $pattern parameter is an array of 2 element, it will assume
  249. * that the first element is the date, and second the time
  250. * and try to find an appropriate pattern and apply
  251. * DateTimeFormatInfo::formatDateTime
  252. * See the tutorial documentation for futher details on the patterns.
  253. *
  254. * @param mixed a pattern.
  255. * @return string a pattern.
  256. * @see DateTimeFormatInfo::formatDateTime()
  257. */
  258. public function getPattern($pattern)
  259. {
  260. if (is_array($pattern) && count($pattern) == 2)
  261. {
  262. return $this->formatInfo->formatDateTime($this->getPattern($pattern[0]), $this->getPattern($pattern[1]));
  263. }
  264. switch ($pattern)
  265. {
  266. case 'd':
  267. return $this->formatInfo->ShortDatePattern;
  268. break;
  269. case 'D':
  270. return $this->formatInfo->LongDatePattern;
  271. break;
  272. case 'p':
  273. return $this->formatInfo->MediumDatePattern;
  274. break;
  275. case 'P':
  276. return $this->formatInfo->FullDatePattern;
  277. break;
  278. case 't':
  279. return $this->formatInfo->ShortTimePattern;
  280. break;
  281. case 'T':
  282. return $this->formatInfo->LongTimePattern;
  283. break;
  284. case 'q':
  285. return $this->formatInfo->MediumTimePattern;
  286. break;
  287. case 'Q':
  288. return $this->formatInfo->FullTimePattern;
  289. break;
  290. case 'f':
  291. return $this->formatInfo->formatDateTime($this->formatInfo->LongDatePattern, $this->formatInfo->ShortTimePattern);
  292. break;
  293. case 'F':
  294. return $this->formatInfo->formatDateTime($this->formatInfo->LongDatePattern, $this->formatInfo->LongTimePattern);
  295. break;
  296. case 'g':
  297. return $this->formatInfo->formatDateTime($this->formatInfo->ShortDatePattern, $this->formatInfo->ShortTimePattern);
  298. break;
  299. case 'G':
  300. return $this->formatInfo->formatDateTime($this->formatInfo->ShortDatePattern, $this->formatInfo->LongTimePattern);
  301. break;
  302. case 'i':
  303. return 'yyyy-MM-dd';
  304. break;
  305. case 'I':
  306. return 'yyyy-MM-dd HH:mm:ss';
  307. break;
  308. case 'M':
  309. case 'm':
  310. return 'MMMM dd';
  311. break;
  312. case 'R':
  313. case 'r':
  314. return 'EEE, dd MMM yyyy HH:mm:ss';
  315. break;
  316. case 's':
  317. return 'yyyy-MM-ddTHH:mm:ss';
  318. break;
  319. case 'u':
  320. return 'yyyy-MM-dd HH:mm:ss z';
  321. break;
  322. case 'U':
  323. return 'EEEE dd MMMM yyyy HH:mm:ss';
  324. break;
  325. case 'Y':
  326. case 'y':
  327. return 'yyyy MMMM';
  328. break;
  329. default :
  330. return $pattern;
  331. }
  332. }
  333. /**
  334. * Returns an easy to parse input pattern
  335. * yy is replaced by yyyy and h by H
  336. *
  337. * @param string pattern.
  338. * @return string input pattern
  339. */
  340. public function getInputPattern($pattern)
  341. {
  342. $pattern = $this->getPattern($pattern);
  343. $pattern = strtr($pattern, array('yyyy' => 'Y', 'h'=>'H', 'z'=>'', 'a'=>''));
  344. $pattern = strtr($pattern, array('yy'=>'yyyy', 'Y'=>'yyyy'));
  345. return trim($pattern);
  346. }
  347. /**
  348. * Tokenize the pattern. The tokens are delimited by group of
  349. * similar characters, e.g. 'aabb' will form 2 tokens of 'aa' and 'bb'.
  350. * Any substrings, starting and ending with a single quote (')
  351. * will be treated as a single token.
  352. *
  353. * @param string pattern.
  354. * @return array string tokens in an array.
  355. */
  356. protected function getTokens($pattern)
  357. {
  358. $char = null;
  359. $tokens = array();
  360. $token = null;
  361. $text = false;
  362. for ($i = 0, $max = strlen($pattern); $i < $max; $i++)
  363. {
  364. if ($char == null || $pattern{$i} == $char || $text)
  365. {
  366. $token .= $pattern{$i};
  367. }
  368. else
  369. {
  370. $tokens[] = str_replace("''", "'", $token);
  371. $token = $pattern{$i};
  372. }
  373. if ($pattern{$i} == "'" && $text == false)
  374. {
  375. $text = true;
  376. }
  377. else if ($text && $pattern{$i} == "'" && $char == "'")
  378. {
  379. $text = true;
  380. }
  381. else if ($text && $char != "'" && $pattern{$i} == "'")
  382. {
  383. $text = false;
  384. }
  385. $char = $pattern{$i};
  386. }
  387. $tokens[] = $token;
  388. return $tokens;
  389. }
  390. // makes a unix date from our incomplete $date array
  391. protected function getUnixDate($date)
  392. {
  393. return getdate(mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']));
  394. }
  395. /**
  396. * Get the year.
  397. * "yy" will return the last two digits of year.
  398. * "yyyy" will return the full integer year.
  399. *
  400. * @param array getdate format.
  401. * @param string a pattern.
  402. * @return string year
  403. */
  404. protected function getYear($date, $pattern = 'yyyy')
  405. {
  406. $year = $date['year'];
  407. switch ($pattern)
  408. {
  409. case 'yy':
  410. return substr($year, 2);
  411. case 'yyyy':
  412. return $year;
  413. default:
  414. throw new sfException('The pattern for year is either "yy" or "yyyy".');
  415. }
  416. }
  417. /**
  418. * Get the month.
  419. * "M" will return integer 1 through 12
  420. * "MM" will return the narrow month name, e.g. "J"
  421. * "MMM" will return the abrreviated month name, e.g. "Jan"
  422. * "MMMM" will return the month name, e.g. "January"
  423. *
  424. * @param array getdate format.
  425. * @param string a pattern.
  426. * @return string month name
  427. */
  428. protected function getMon($date, $pattern = 'M')
  429. {
  430. $month = $date['mon'];
  431. switch ($pattern)
  432. {
  433. case 'M':
  434. return $month;
  435. case 'MM':
  436. return str_pad($month, 2, '0', STR_PAD_LEFT);
  437. case 'MMM':
  438. return $this->formatInfo->AbbreviatedMonthNames[$month - 1];
  439. break;
  440. case 'MMMM':
  441. return $this->formatInfo->MonthNames[$month - 1];
  442. default:
  443. throw new sfException('The pattern for month is "M", "MM", "MMM", or "MMMM".');
  444. }
  445. }
  446. /**
  447. * Get the day of the week.
  448. * "E" will return integer 0 (for Sunday) through 6 (for Saturday).
  449. * "EE" will return the narrow day of the week, e.g. "M"
  450. * "EEE" will return the abrreviated day of the week, e.g. "Mon"
  451. * "EEEE" will return the day of the week, e.g. "Monday"
  452. *
  453. * @param array getdate format.
  454. * @param string a pattern.
  455. * @return string day of the week.
  456. */
  457. protected function getWday($date, $pattern = 'EEEE')
  458. {
  459. // if the $date comes from our home-made get date
  460. if (!isset($date['wday']))
  461. {
  462. $date = $this->getUnixDate($date);
  463. }
  464. $day = $date['wday'];
  465. switch ($pattern)
  466. {
  467. case 'E':
  468. return $day;
  469. break;
  470. case 'EE':
  471. return $this->formatInfo->NarrowDayNames[$day];
  472. case 'EEE':
  473. return $this->formatInfo->AbbreviatedDayNames[$day];
  474. break;
  475. case 'EEEE':
  476. return $this->formatInfo->DayNames[$day];
  477. break;
  478. default:
  479. throw new sfException('The pattern for day of the week is "E", "EE", "EEE", or "EEEE".');
  480. }
  481. }
  482. /**
  483. * Get the day of the month.
  484. * "d" for non-padding, "dd" will always return 2 characters.
  485. *
  486. * @param array getdate format.
  487. * @param string a pattern.
  488. * @return string day of the month
  489. */
  490. protected function getMday($date, $pattern = 'd')
  491. {
  492. $day = $date['mday'];
  493. switch ($pattern)
  494. {
  495. case 'd':
  496. return $day;
  497. case 'dd':
  498. return str_pad($day, 2, '0', STR_PAD_LEFT);
  499. case 'dddd':
  500. return $this->getWday($date);
  501. default:
  502. throw new sfException('The pattern for day of the month is "d", "dd" or "dddd".');
  503. }
  504. }
  505. /**
  506. * Get the era. i.e. in gregorian, year > 0 is AD, else BC.
  507. *
  508. * @todo How to support multiple Eras?, e.g. Japanese.
  509. * @param array getdate format.
  510. * @param string a pattern.
  511. * @return string era
  512. */
  513. protected function getEra($date, $pattern = 'G')
  514. {
  515. if ($pattern != 'G')
  516. {
  517. throw new sfException('The pattern for era is "G".');
  518. }
  519. return $this->formatInfo->getEra($date['year'] > 0 ? 1 : 0);
  520. }
  521. /**
  522. * Get the hours in 24 hour format, i.e. [0-23].
  523. * "H" for non-padding, "HH" will always return 2 characters.
  524. *
  525. * @param array getdate format.
  526. * @param string a pattern.
  527. * @return string hours in 24 hour format.
  528. */
  529. protected function getHours($date, $pattern = 'H')
  530. {
  531. $hour = $date['hours'];
  532. switch ($pattern)
  533. {
  534. case 'H':
  535. return $hour;
  536. case 'HH':
  537. return str_pad($hour, 2, '0', STR_PAD_LEFT);
  538. default:
  539. throw new sfException('The pattern for 24 hour format is "H" or "HH".');
  540. }
  541. }
  542. /**
  543. * Get the AM/PM designator, 12 noon is PM, 12 midnight is AM.
  544. *
  545. * @param array getdate format.
  546. * @param string a pattern.
  547. * @return string AM or PM designator
  548. */
  549. protected function getAMPM($date, $pattern = 'a')
  550. {
  551. if ($pattern != 'a')
  552. {
  553. throw new sfException('The pattern for AM/PM marker is "a".');
  554. }
  555. return $this->formatInfo->AMPMMarkers[intval($date['hours'] / 12)];
  556. }
  557. /**
  558. * Get the hours in 12 hour format.
  559. * "h" for non-padding, "hh" will always return 2 characters.
  560. *
  561. * @param array getdate format.
  562. * @param string a pattern.
  563. * @return string hours in 12 hour format.
  564. */
  565. protected function getHour12($date, $pattern = 'h')
  566. {
  567. $hour = $date['hours'];
  568. $hour = ($hour == 12 | $hour == 0) ? 12 : ($hour) % 12;
  569. switch ($pattern)
  570. {
  571. case 'h':
  572. return $hour;
  573. case 'hh':
  574. return str_pad($hour, 2, '0', STR_PAD_LEFT);
  575. default:
  576. throw new sfException('The pattern for 24 hour format is "H" or "HH".');
  577. }
  578. }
  579. /**
  580. * Get the minutes.
  581. * "m" for non-padding, "mm" will always return 2 characters.
  582. *
  583. * @param array getdate format.
  584. * @param string a pattern.
  585. * @return string minutes.
  586. */
  587. protected function getMinutes($date, $pattern = 'm')
  588. {
  589. $minutes = $date['minutes'];
  590. switch ($pattern)
  591. {
  592. case 'm':
  593. return $minutes;
  594. case 'mm':
  595. return str_pad($minutes, 2, '0', STR_PAD_LEFT);
  596. default:
  597. throw new sfException('The pattern for minutes is "m" or "mm".');
  598. }
  599. }
  600. /**
  601. * Get the seconds.
  602. * "s" for non-padding, "ss" will always return 2 characters.
  603. *
  604. * @param array getdate format.
  605. * @param string a pattern.
  606. * @return string seconds
  607. */
  608. protected function getSeconds($date, $pattern = 's')
  609. {
  610. $seconds = $date['seconds'];
  611. switch ($pattern)
  612. {
  613. case 's':
  614. return $seconds;
  615. case 'ss':
  616. return str_pad($seconds, 2, '0', STR_PAD_LEFT);
  617. default:
  618. throw new sfException('The pattern for seconds is "s" or "ss".');
  619. }
  620. }
  621. /**
  622. * Get the timezone from the server machine.
  623. *
  624. * @todo How to get the timezone for a different region?
  625. * @param array getdate format.
  626. * @param string a pattern.
  627. * @return string time zone
  628. */
  629. protected function getTimeZone($date, $pattern = 'z')
  630. {
  631. if ($pattern != 'z')
  632. {
  633. throw new sfException('The pattern for time zone is "z".');
  634. }
  635. return @date('T', @mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']));
  636. }
  637. /**
  638. * Get the day in the year, e.g. [1-366]
  639. *
  640. * @param array getdate format.
  641. * @param string a pattern.
  642. * @return int hours in AM/PM format.
  643. */
  644. protected function getYday($date, $pattern = 'D')
  645. {
  646. if ($pattern != 'D')
  647. {
  648. throw new sfException('The pattern for day in year is "D".');
  649. }
  650. return $date['yday'];
  651. }
  652. /**
  653. * Get day in the month.
  654. *
  655. * @param array getdate format.
  656. * @param string a pattern.
  657. * @return int day in month
  658. */
  659. protected function getDayInMonth($date, $pattern = 'FF')
  660. {
  661. switch ($pattern)
  662. {
  663. case 'F':
  664. return @date('j', @mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']));
  665. break;
  666. case 'FF':
  667. return @date('d', @mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']));
  668. break;
  669. default:
  670. throw new sfException('The pattern for day in month is "F" or "FF".');
  671. }
  672. }
  673. /**
  674. * Get the week in the year.
  675. *
  676. * @param array getdate format.
  677. * @param string a pattern.
  678. * @return int week in year
  679. */
  680. protected function getWeekInYear($date, $pattern = 'w')
  681. {
  682. if ($pattern != 'w')
  683. {
  684. throw new sfException('The pattern for week in year is "w".');
  685. }
  686. return @date('W', @mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year']));
  687. }
  688. /**
  689. * Get week in the month.
  690. *
  691. * @param array getdate format.
  692. * @return int week in month
  693. */
  694. protected function getWeekInMonth($date, $pattern = 'W')
  695. {
  696. if ($pattern != 'W')
  697. {
  698. throw new sfException('The pattern for week in month is "W".');
  699. }
  700. return @date('W', @mktime(0, 0, 0, $date['mon'], $date['mday'], $date['year'])) - date('W', mktime(0, 0, 0, $date['mon'], 1, $date['year']));
  701. }
  702. /**
  703. * Get the hours [1-24].
  704. *
  705. * @param array getdate format.
  706. * @param string a pattern.
  707. * @return int hours [1-24]
  708. */
  709. protected function getHourInDay($date, $pattern = 'k')
  710. {
  711. if ($pattern != 'k')
  712. {
  713. throw new sfException('The pattern for hour in day is "k".');
  714. }
  715. return $date['hours'] + 1;
  716. }
  717. /**
  718. * Get the hours in AM/PM format, e.g [1-12]
  719. *
  720. * @param array getdate format.
  721. * @param string a pattern.
  722. * @return int hours in AM/PM format.
  723. */
  724. protected function getHourInAMPM($date, $pattern = 'K')
  725. {
  726. if ($pattern != 'K')
  727. {
  728. throw new sfException('The pattern for hour in AM/PM is "K".');
  729. }
  730. return ($date['hours'] + 1) % 12;
  731. }
  732. }