DatetimeLib.php 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836
  1. <?php
  2. /**
  3. * TODO: include all helper methods
  4. *
  5. *
  6. * 2011-03-03 ms
  7. */
  8. class DatetimeLib {
  9. protected $userOffset = null;
  10. protected $daylightSavings = false;
  11. public function __construct() {
  12. $i18n = Configure::read('Localization');
  13. if (!empty($i18n['time_offset'])) {
  14. $this->userOffset = (int)$i18n['time_offset'];
  15. }
  16. if (!empty($i18n['daylight_savings'])) {
  17. $this->daylightSavings = (bool)$i18n['daylight_savings'];
  18. }
  19. }
  20. /** custom stuff **/
  21. /**
  22. * calculate the difference between two dates
  23. * should only be used for < month (due to the different month lenghts it gets fuzzy)
  24. * @param mixed $start (db format or timestamp)
  25. * @param mixex §end (db format or timestamp)
  26. * @return int: the distance in seconds
  27. * 2011-03-03 ms
  28. */
  29. public function difference($startTime = null, $endTime = null, $options = array()) {
  30. if (!is_int($startTime)) {
  31. $startTime = strtotime($startTime);
  32. }
  33. if (!is_int($endTime)) {
  34. $endTime = strtotime($endTime);
  35. }
  36. //@FIXME: make it work for > month
  37. return abs($endTime - $startTime);
  38. }
  39. /**
  40. * @param start date (if empty, use today)
  41. * @param end date (if empty, use today)
  42. * start and end cannot be both empty!
  43. * @param accuracy (year only = 0, incl months/days = 2)
  44. * if > 0, returns array!!! ('days'=>x,'months'=>y,'years'=>z)
  45. *
  46. * does this work too?
  47. $now = mktime(0,0,0,date("m"),date("d"),date("Y"));
  48. $birth = mktime(0,0,0,$monat,$tag,$jahr);
  49. $age = intval(($now - $birth) / (3600 * 24 * 365));
  50. * @return int age (0 if both timestamps are equal or empty, -1 on invalid dates)
  51. * 2009-03-12 ms
  52. */
  53. public function age($start = null, $end = null, $accuracy = 0) {
  54. $age = 0;
  55. if (empty($start) && empty($end) || $start == $end) {
  56. return 0;
  57. }
  58. if (empty($start)) {
  59. list($yearS, $monthS, $dayS) = explode('-', date(FORMAT_DB_DATE));
  60. } else {
  61. $startDate = $this->fromString($start);
  62. $yearS = date('Y', $startDate);
  63. $monthS = date('m', $startDate);
  64. $dayS = date('d', $startDate);
  65. if (!checkdate($monthS, $dayS, $yearS)) {
  66. return -1;
  67. }
  68. }
  69. if (empty($end)) {
  70. list($yearE, $monthE, $dayE) = explode('-', date(FORMAT_DB_DATE));
  71. } else {
  72. $endDate = $this->fromString($end);
  73. $yearE = date('Y', $endDate);
  74. $monthE = date('m', $endDate);
  75. $dayE = date('d', $endDate);
  76. if (!checkdate($monthE, $dayE, $yearE)) {
  77. return -1;
  78. }
  79. }
  80. //$startDate = mktime(0,0,0,$monthS,$dayS,$yearS);
  81. //$endDate = mktime(0,0,0,$monthE,$dayE,$yearE);
  82. //$age = intval(($endDate - $startDate) / (3600 * 24 * 365));
  83. //$age = $this->timef($endDate-$startDate, 'Y'); # !!! timef function
  84. $n_tag = $dayE;
  85. $n_monat = $monthE;
  86. $n_jahr = $yearE;
  87. $g_tag = $dayS;
  88. $g_monat = $monthS;
  89. $g_jahr = $yearS;
  90. $g_date = mktime(0, 0, 0, $g_tag, $g_monat, $g_jahr);
  91. if (($n_monat>$g_monat)||(($n_monat == $g_monat)&&($n_tag>$g_tag))||(($n_monat == $g_monat)&&($n_tag==$g_tag))) {
  92. $age = $n_jahr-$g_jahr; // is correct if one already had his birthday this year
  93. } else {
  94. $age = $n_jahr-$g_jahr-1; // is correct if one didnt have his birthday yet in this year
  95. }
  96. return $age;
  97. //TODO: test this short method
  98. //return (date("Y",time()) - $val);
  99. }
  100. /**
  101. * try to return the age only with the year available
  102. * can be e.g. 22/23
  103. * @param int $year
  104. * @param int $month (optional)
  105. * 2011-03-11 ms
  106. */
  107. public function ageByYear($year, $month = null) {
  108. if ($month === null) {
  109. $maxAge = $this->age(mktime(0,0,0,1,1,$year));
  110. $minAge = $this->age(mktime(23,59,59,12,31,$year));
  111. $ages = array_unique(array($minAge, $maxAge));
  112. return implode('/', $ages);
  113. }
  114. if (date('n') == $month) {
  115. $maxAge = $this->age(mktime(0, 0, 0, $month, 1, $year));
  116. $minAge = $this->age(mktime(23, 59, 59, $month, $this->daysInMonth($year, $month), $year));
  117. $ages = array_unique(array($minAge, $maxAge));
  118. return implode('/', $ages);
  119. }
  120. return $this->age(mktime(0, 0, 0, $month, 1, $year));
  121. }
  122. /**
  123. * 2011-11-22 lb
  124. */
  125. public function ageByHoroscope($year, $sign) {
  126. App::uses('ZodiacLib', 'Tools.Misc');
  127. $Zodiac = new ZodiacLib();
  128. $range = $Zodiac->getRange($sign);
  129. // undefined
  130. if ($sign == ZodiacLib::SIGN_CAPRICORN) {
  131. return array(date('Y') - $year - 1, date('Y') - $year);
  132. }
  133. // not over
  134. elseif($range[0][0] > date('m') || ($range[0][0] == date('m') && $range[0][1] > date('d'))) {
  135. return date('Y') - $year - 1;
  136. }
  137. // over
  138. elseif ($range[1][0] < date('m') || ($range[1][0] == date('m') && $range[1][1] <= date('d'))) {
  139. return date('Y') - $year;
  140. } else {
  141. return array(date('Y') - $year - 1, date('Y') - $year);
  142. }
  143. }
  144. /**
  145. * rounded age depended on steps (e.g. age 16 with steps = 10 => "11-20")
  146. * @FIXME
  147. * TODO: move to helper?
  148. * 2011-04-07 ms
  149. */
  150. public function ageRange($year, $month = null, $day = null, $steps = 1) {
  151. if ($month == null && $day == null) {
  152. $age = date('Y') - $year - 1;
  153. }
  154. elseif($day == null) {
  155. if ($month >= date('m'))
  156. $age = date('Y') - $year - 1;
  157. else
  158. $age = date('Y') - $year;
  159. }
  160. else {
  161. if ($month > date('m') || ($month == date('m') && $day > date('d')))
  162. $age = date('Y') - $year - 1;
  163. else
  164. $age = date('Y') - $year;
  165. }
  166. if ($age % $steps == 0) {
  167. $lowerRange = $age - $steps + 1;
  168. $upperRange = $age;
  169. }
  170. else {
  171. $lowerRange = $age - ($age % $steps) + 1;
  172. $upperRange = $age - ($age % $steps) + $steps;
  173. }
  174. if ($lowerRange == $upperRange)
  175. return $upperRange;
  176. else
  177. return array($lowerRange, $upperRange);
  178. }
  179. /**
  180. * return the days of a given month
  181. * 2011-11-03 ms
  182. */
  183. public function daysInMonth($year, $month) {
  184. return date("t", mktime(0, 0, 0, $month, 1, $year));
  185. }
  186. /**
  187. * Calendar Week (current week of the year)
  188. * @param date in DB format - if none is passed, current day is used
  189. * @param int relative - weeks relative to the date (+1 next, -1 previous etc)
  190. * @TODO: use timestamp - or make the function able to use timestamps at least (besides dateString)
  191. *
  192. * Mit date('W', $time) (großes W!) bekommst die ISO6801-Wochennummer des angegebenen Zeitpunkts, das entspricht der Europäischen Kalenderwoche - mit einer Ausnahme: Daten die zur letzten Kalenderwoche des vorherigen Jahres gehören, liefern die 0 zurück; in dem Fall solltest du dann die KW des 31.12. des Vorjahres ermitteln.
  193. */
  194. public function cweek($dateString = null, $relative = 0) {
  195. //$time = $this->fromString($dateString);
  196. if (!empty($dateString)) {
  197. //pr ($dateString);
  198. $date = explode(' ', $dateString);
  199. list ($y, $m, $d) = explode('-', $date[0]);
  200. $t = mktime(0, 0, 0, $m, $d, $y);
  201. } else {
  202. $d = date('d');
  203. $m = date('m');
  204. $y = date('Y');
  205. $t = time();
  206. }
  207. $relative = (int)$relative;
  208. if ($relative != 0) {
  209. $t += WEEK*$relative; // 1day * 7 * relativeWeeks
  210. }
  211. if (0==($kw=date('W', $t))) {
  212. $kw = 1+date($t-DAY*date('w', $t), 'W');
  213. $y--;
  214. }
  215. //echo "Der $d.$m.$y liegt in der Kalenderwoche $kw/$y";
  216. return $kw.'/'.$y;
  217. }
  218. /**
  219. * return the timestamp to a day in a specific cweek
  220. * 0=sunday to 7=saturday (default)
  221. * @return timestamp of the weekDay
  222. * @FIXME: offset
  223. * not needed, use localDate!
  224. */
  225. public function cweekDay($cweek, $year, $day, $offset = 0) {
  226. $cweekBeginning = $this->cweekBeginning($year, $cweek);
  227. return $cweekBeginning + $day * DAY;
  228. }
  229. /**
  230. * @FIXME ???
  231. * Get number of days since the start of the week.
  232. * 1 = monday, 7 = sunday ? should be 0=sunday to 7=saturday (default)
  233. * @param int $num Number of day.
  234. * @return int Days since the start of the week.
  235. */
  236. public function cweekMod($num, $offset = 0) {
  237. $base = 7;
  238. return ($num - $base*floor($num/$base));
  239. }
  240. /**
  241. * calculate the beginning of a calenderweek
  242. * if no cweek is given get the beginning of the first week of the year
  243. * @param year (format xxxx)
  244. * @param cweek (optional, defaults to first, range 1...52/53)
  245. * 2011-03-07 ms
  246. */
  247. public function cweekBeginning($year, $cweek = null) {
  248. if ((int)$cweek <= 1 || (int)$cweek > self::cweeks($year)) {
  249. $first = mktime(0,0,0,1,1, $year);
  250. $wtag = date('w', $first);
  251. if ($wtag<=4) {
  252. /*Donnerstag oder kleiner: auf den Montag zurückrechnen.*/
  253. $firstmonday = mktime(0,0,0,1,1-($wtag-1),$year);
  254. } elseif ($wtag!=1) {
  255. /*auf den Montag nach vorne rechnen.*/
  256. $firstmonday = mktime(0,0,0,1,1+(7-$wtag+1),$year);
  257. } else {
  258. $firstmonday = $first;
  259. }
  260. return $firstmonday;
  261. }
  262. $monday = strtotime($year.'W'.str_pad($cweek, 2, '0', STR_PAD_LEFT).'1');
  263. return $monday;
  264. }
  265. /**
  266. * calculate the ending of a calenderweek
  267. * if no cweek is given get the ending of the last week of the year
  268. * @param year (format xxxx)
  269. * @param cweek (optional, defaults to last, range 1...52/53)
  270. * 2011-03-07 ms
  271. */
  272. public function cweekEnding($year, $cweek = null) {
  273. if ((int)$cweek < 1 || (int)$cweek >= self::cweeks($year)) {
  274. return self::cweekBeginning($year+1)-1;
  275. }
  276. return self::cweekBeginning($year, intval($cweek)+1)-1;
  277. }
  278. /**
  279. * calculate the amount of calender weeks in a year
  280. * @param year (format xxxx, defaults to current year)
  281. * @return int: 52 or 53
  282. * 2011-03-07 ms
  283. */
  284. public function cweeks($year = null) {
  285. if ($year === null) {
  286. $year = date('Y');
  287. }
  288. return date('W', mktime(23, 59, 59, 12, 28, $year));
  289. }
  290. /**
  291. * get the age bounds (min, max) as timestamp that would result in the given age(s)
  292. * note: expects valid age (> 0 and < 120)
  293. * @param $firstAge
  294. * @param $secondAge (defaults to first one if not specified)
  295. * @return array('min'=>$min, 'max'=>$max);
  296. * 2011-07-06 ms
  297. */
  298. public function ageBounds($firstAge, $secondAge = null, $returnAsString = false, $relativeTime = null) {
  299. if ($secondAge === null) {
  300. $secondAge = $firstAge;
  301. }
  302. //TODO: other relative time then today should work as well
  303. $max = mktime(23, 23, 59, date('m'), date('d'), date('Y')-$firstAge); // time()-($firstAge+1)*YEAR;
  304. $min = mktime(0, 0, 1, date('m'), date('d')+1, date('Y')-$secondAge-1); // time()+DAY-$secondAge*YEAR;
  305. if ($returnAsString) {
  306. $max = date(FORMAT_DB_DATE, $max);
  307. $min = date(FORMAT_DB_DATE, $min);
  308. }
  309. return array('min'=>$min, 'max'=>$max);
  310. }
  311. /**
  312. * for birthdays etc
  313. * @param date
  314. * @param string days with +-
  315. * @param options
  316. * 2011-03-03 ms
  317. */
  318. public function isInRange($dateString, $seconds, $options = array()) {
  319. //$newDate = is_int($dateString) ? $dateString : strtotime($dateString);
  320. //$newDate += $seconds;
  321. $newDate = time();
  322. return $this->difference($dateString, $newDate) <= $seconds;
  323. }
  324. /**
  325. * outputs Date(time) Sting nicely formatted (+ localized!)
  326. * @param string $dateString,
  327. * @param string $format (YYYY-MM-DD, DD.MM.YYYY)
  328. * @param array $options
  329. * - userOffset: User's offset from GMT (in hours)
  330. * - default (defaults to "-----")
  331. * 2009-03-31 ms
  332. */
  333. public function localDate($dateString = null, $format = null, $options = array()) {
  334. $defaults = array('default'=>'-----', 'userOffset'=>$this->userOffset);
  335. $options = array_merge($defaults, $options);
  336. $date = null;
  337. if ($dateString !== null) {
  338. $date = $this->fromString($dateString, $options['userOffset']);
  339. }
  340. if ($date === null || $date === false || $date <= 0) {
  341. return $options['default'];
  342. }
  343. if ($format === null) {
  344. if (is_int($dateString) || strpos($dateString, ' ') !== false) {
  345. $format = FORMAT_LOCAL_YMDHM;
  346. } else {
  347. $format = FORMAT_LOCAL_YMD;
  348. }
  349. }
  350. return strftime($format, $date);
  351. }
  352. /**
  353. * outputs Date(time) Sting nicely formatted
  354. * @param string $dateString,
  355. * @param string $format (YYYY-MM-DD, DD.MM.YYYY)
  356. * @param array $options
  357. * - userOffset: User's offset from GMT (in hours)
  358. * - default (defaults to "-----")
  359. * 2009-03-31 ms
  360. */
  361. public function niceDate($dateString = null, $format = null, $options = array()) {
  362. $defaults = array('default'=>'-----', 'userOffset'=>$this->userOffset);
  363. $options = array_merge($defaults, $options);
  364. $date = null;
  365. if ($dateString !== null) {
  366. $date = $this->fromString($dateString, $options['userOffset']);
  367. }
  368. if ($date === null || $date === false || $date <= 0) {
  369. return $options['default'];
  370. }
  371. if ($format === null) {
  372. if (is_int($dateString) || strpos($dateString, ' ') !== false) {
  373. $format = FORMAT_NICE_YMDHM;
  374. } else {
  375. $format = FORMAT_NICE_YMD;
  376. }
  377. }
  378. $ret = date($format, $date);
  379. if (!empty($options['oclock']) && $options['oclock']) {
  380. switch ($format) {
  381. case FORMAT_NICE_YMDHM:
  382. case FORMAT_NICE_YMDHMS:
  383. case FORMAT_NICE_YMDHM:
  384. case FORMAT_NICE_HM:
  385. case FORMAT_NICE_HMS:
  386. $ret .= ' '.__('o\'clock');
  387. break;
  388. }
  389. }
  390. return $ret;
  391. }
  392. /**
  393. * return the translation to a specific week day
  394. * @param int $day:
  395. * 0=sunday to 7=saturday (default numbers)
  396. * @param bool $abbr (if abbreviation should be returned)
  397. * @param offset: 0-6 (defaults to 0) [1 => 1=monday to 7=sunday]
  398. * @return string $translatedText
  399. * 2011-12-07 ms
  400. */
  401. public function day($day, $abbr = false, $offset = 0) {
  402. $days = array(
  403. 'long' => array(
  404. 'Sunday',
  405. 'Monday',
  406. 'Tuesday',
  407. 'Wednesday',
  408. 'Thursday',
  409. 'Friday',
  410. 'Saturday'
  411. ),
  412. 'short' => array(
  413. 'Sun',
  414. 'Mon',
  415. 'Tue',
  416. 'Wed',
  417. 'Thu',
  418. 'Fri',
  419. 'Sat'
  420. )
  421. );
  422. $day = (int) $day;
  423. pr($day);
  424. if ($offset) {
  425. $day = ($day + $offset) % 7;
  426. }
  427. pr($day);
  428. if ($abbr) {
  429. return __($days['short'][$day]);
  430. }
  431. return __($days['long'][$day]);
  432. }
  433. /**
  434. * return the translation to a specific week day
  435. * @param int $month:
  436. * 1..12
  437. * @param bool $abbr (if abbreviation should be returned)
  438. * @param array $options
  439. * - appendDot (only for 3 letter abbr; defaults to false)
  440. * @return string $translatedText
  441. * 2011-12-07 ms
  442. */
  443. public function month($month, $abbr = false, $options = array()) {
  444. $months = array(
  445. 'long' => array(
  446. 'January',
  447. 'February',
  448. 'March',
  449. 'April',
  450. 'May',
  451. 'June',
  452. 'July',
  453. 'August',
  454. 'September',
  455. 'October',
  456. 'November',
  457. 'December'
  458. ),
  459. 'short' => array(
  460. 'Jan',
  461. 'Feb',
  462. 'Mar',
  463. 'Apr',
  464. 'May',
  465. 'Jun',
  466. 'Jul',
  467. 'Aug',
  468. 'Sep',
  469. 'Oct',
  470. 'Nov',
  471. 'Dec'
  472. ),
  473. );
  474. $month = (int) ($month - 1);
  475. if (!$abbr) {
  476. return __($months['long'][$month]);
  477. }
  478. $monthName = __($months['short'][$month]);
  479. if (!empty($options['appendDot']) && strlen(__($months['long'][$month])) > 3) {
  480. $monthName .= '.';
  481. }
  482. return $monthName;
  483. }
  484. /**
  485. * @return array (for forms etc)
  486. */
  487. public function months($monthKeys = array(), $options = array()) {
  488. if (!$monthKeys) {
  489. $monthKeys = range(1, 12);
  490. }
  491. $res = array();
  492. $abbr = isset($options['abbr']) ? $options['abbr'] : false;
  493. foreach ($monthKeys as $key) {
  494. $res[str_pad($key, 2, '0', STR_PAD_LEFT)] = self::month($key, $abbr, $options);
  495. }
  496. return $res;
  497. }
  498. /**
  499. * weekdays
  500. * @return array (for forms etc)
  501. */
  502. public function days($dayKeys = array(), $options = array()) {
  503. if (!$dayKeys) {
  504. $dayKeys = range(0, 6);
  505. }
  506. $res = array();
  507. $abbr = isset($options['abbr']) ? $options['abbr'] : false;
  508. $offset = isset($options['offset']) ? $options['offset'] : 0;
  509. foreach ($dayKeys as $key) {
  510. $res[$key] = self::day($key, $abbr, $offset);
  511. }
  512. return $res;
  513. }
  514. /**
  515. * can convert time from one unit to another
  516. * @param int INT | time
  517. * @param from CHAR
  518. * @param to CHAR
  519. * @param options: acc=>INT [accuracy], showZero=>BOOL, returnArray=>BOOL
  520. * 2008-11-06 ms
  521. */
  522. public function convertTime($int, $from, $to, $options = array()) {
  523. $accuracy = 0; # 0 = only the "to"-element, 1..n = higher accurancy
  524. $showZero = false; # show only the non-zero elements
  525. $returnArray = false; # return as array instead of as string
  526. if (!empty($options)) {
  527. if (isset($options['acc'])) {
  528. $accuracy = (int)$options['acc'];
  529. }
  530. if (isset($options['showZero'])) {
  531. $showZero = (int)$options['showZero'];
  532. }
  533. if (isset($options['returnArray'])) {
  534. $return = ($options['returnArray']===true?true:false);
  535. }
  536. }
  537. $times = array(
  538. 's'=>'0',
  539. 'm'=>'1',
  540. 'h'=>'2',
  541. 'd'=>'3',
  542. 'w'=>'4',
  543. 'm'=>'5',
  544. 'y'=>'6',
  545. );
  546. $options = array(
  547. '0'=>array(
  548. 'steps'=>array('1'=>60,'2'=>3600,'3'=>86400,'4'=>86400*7,'5'=>86400*30,'6'=>86400*365),
  549. 'down'=>0,
  550. 'up'=>60,
  551. 'short'=>'s',
  552. 'long'=>'seconds'
  553. ),
  554. '1'=>array(
  555. 'steps'=>array('0'=>60,'2'=>60,'3'=>60*24,'4'=>60*24*7,'5'=>60*24*30,'6'=>60*24*365),
  556. 'down'=>60,
  557. 'up'=>60,
  558. 'short'=>'m',
  559. 'long'=>'minutes'
  560. ),
  561. '2'=>array(
  562. 'steps'=>array('0'=>3600,'1'=>60,'3'=>24,'4'=>24*7,'5'=>24*30,'6'=>24*365),
  563. 'down'=>60,
  564. 'up'=>24,
  565. 'short'=>'h',
  566. 'long'=>'hours'
  567. ),
  568. '3'=>array(
  569. 'steps'=>array('0'=>86400,'1'=>3600,'2'=>24,'4'=>7,'5'=>30,'6'=>365),
  570. 'down'=>24,
  571. 'up'=>7,
  572. 'short'=>'d',
  573. 'long'=>'days'
  574. ),
  575. '4'=>array(
  576. 'steps'=>array('0'=>86400*7,'1'=>60*24*7,'2'=>24*7,'3'=>7,'5'=>4.2,'6'=>52),
  577. 'down'=>7,
  578. 'up'=>4.2,
  579. 'short'=>'w',
  580. 'long'=>'weeks'
  581. ),
  582. '5'=>array(
  583. 'steps'=>array('0'=>86400*30,'1'=>60*24*30,'2'=>24*30,'3'=>30,'4'=>4.2,'6'=>12),
  584. 'down'=>4.2,
  585. 'up'=>12,
  586. 'short'=>'m',
  587. 'long'=>'months'
  588. ),
  589. '6'=>array(
  590. 'steps'=>array('0'=>86400*365,'1'=>60*24*365,'2'=>24*365,'3'=>365,'4'=>52,'5'=>12),
  591. 'down'=>12,
  592. 'up'=>0,
  593. 'short'=>'y',
  594. 'long'=>'years'
  595. ),
  596. );
  597. //echo $options[0]['steps']['4'];
  598. if (array_key_exists($from,$times) && array_key_exists($to,$times)) {
  599. $begin = $times[$from];
  600. $end = $times[$to];
  601. //echo $begin-$end.BR;
  602. }
  603. $minuten = $int;
  604. if ($minuten<60) {
  605. return $minuten.'min';
  606. }
  607. $calculated = floor($minuten/60)."h ".($minuten%60)."min";
  608. if ($returnArray) {
  609. // return as array
  610. } else {
  611. // convert to the desired string
  612. }
  613. return $calculated;
  614. }
  615. /**
  616. * @deprecated
  617. * NICHT TESTEN!
  618. */
  619. public function otherOne() {
  620. $day = floor($anz_sekunden/86400);
  621. $hours = floor(($anz_sekunden-(floor($anz_sekunden/86400)*86400))/3600);
  622. $minutes = floor(($anz_sekunden-(floor($anz_sekunden/3600)*3600))/60);
  623. $seconds = floor($anz_sekunden-(floor($anz_sekunden/60))*60);
  624. if ($day < 10) {
  625. $day = '0'.$day;
  626. }
  627. if ($hours < 10) {
  628. $hours = '0'.$hours;
  629. }
  630. if ($minutes < 10) {
  631. $minutes = '0'.$minutes;
  632. }
  633. if ($seconds < 10) {
  634. $seconds = '0'.$seconds;
  635. }
  636. if ($day > 0) {
  637. $zeit_ausgabe = $day.":".$hours.":".$minutes.":".$seconds;
  638. } else {
  639. $zeit_ausgabe = $hours.":".$minutes.":".$seconds." h";
  640. }
  641. }
  642. /**
  643. * Returns the difference between a time and now in a "fuzzy" way.
  644. * Note that unlike [span], the "local" timestamp will always be the
  645. * current time. Displaying a fuzzy time instead of a date is usually
  646. * faster to read and understand.
  647. *
  648. * $span = fuzzy(time() - 10); // "moments ago"
  649. * $span = fuzzy(time() + 20); // "in moments"
  650. *
  651. * @param integer "remote" timestamp
  652. * @return string
  653. */
  654. public function fuzzy($timestamp) {
  655. // Determine the difference in seconds
  656. $offset = abs(time() - $timestamp);
  657. return $this->fuzzyFromOffset($offset, $timestamp <= time());
  658. }
  659. /**
  660. * @param int $offset in seconds
  661. * @param boolean $past (defaults to null: return plain text)
  662. * - new: if not boolean but a string use this as translating text
  663. * @return string $text (i18n!)
  664. * 2011-03-06 ms
  665. */
  666. public function fuzzyFromOffset($offset, $past = null) {
  667. if ($offset <= MINUTE) {
  668. $span = 'moments';
  669. } elseif ($offset < (MINUTE * 20)) {
  670. $span = 'a few minutes';
  671. } elseif ($offset < HOUR) {
  672. $span = 'less than an hour';
  673. } elseif ($offset < (HOUR * 4)) {
  674. $span = 'a couple of hours';
  675. } elseif ($offset < DAY) {
  676. $span = 'less than a day';
  677. } elseif ($offset < (DAY * 2)) {
  678. $span = 'about a day';
  679. } elseif ($offset < (DAY * 4)) {
  680. $span = 'a couple of days';
  681. } elseif ($offset < WEEK) {
  682. $span = 'less than a week';
  683. } elseif ($offset < (WEEK * 2)) {
  684. $span = 'about a week';
  685. } elseif ($offset < MONTH) {
  686. $span = 'less than a month';
  687. } elseif ($offset < (MONTH * 2)) {
  688. $span = 'about a month';
  689. } elseif ($offset < (MONTH * 4)) {
  690. $span = 'a couple of months';
  691. } elseif ($offset < YEAR) {
  692. $span = 'less than a year';
  693. } elseif ($offset < (YEAR * 2)) {
  694. $span = 'about a year';
  695. } elseif ($offset < (YEAR * 4)) {
  696. $span = 'a couple of years';
  697. } elseif ($offset < (YEAR * 8)) {
  698. $span = 'a few years';
  699. } elseif ($offset < (YEAR * 12)) {
  700. $span = 'about a decade';
  701. } elseif ($offset < (YEAR * 24)) {
  702. $span = 'a couple of decades';
  703. } elseif ($offset < (YEAR * 64)) {
  704. $span = 'several decades';
  705. } else {
  706. $span = 'a long time';
  707. }
  708. if ($past === true) {
  709. // This is in the past
  710. return __('%s ago', __($span));
  711. } elseif ($past === false) {
  712. // This in the future
  713. return __('in %s', __($span));
  714. } elseif ($past !== null) {
  715. // Custom translation
  716. return __($past, __($span));
  717. }
  718. return __($span);
  719. }
  720. /**
  721. * time length to human readable format
  722. * @param int $seconds
  723. * @param string format: format
  724. * @param options
  725. * - boolean v: verbose
  726. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  727. * - int: accuracy (how many sub-formats displayed?) //TODO
  728. * 2009-11-21 ms
  729. * @see timeAgoInWords()
  730. */
  731. public function lengthOfTime($seconds, $format = null, $options = array()) {
  732. $defaults = array('verbose'=>true, 'zero'=>false, 'separator'=>', ', 'default'=>'');
  733. $ret = '';
  734. $j = 0;
  735. $options = array_merge($defaults, $options);
  736. if (!$options['verbose']) {
  737. $s = array(
  738. 'm' => 'mth',
  739. 'd' => 'd',
  740. 'h' => 'h',
  741. 'i' => 'm',
  742. 's' => 's'
  743. );
  744. $p = $s;
  745. } else {
  746. $s = array(
  747. 'm' => ' '.__('Month'), # translated
  748. 'd' => ' '.__('Day'),
  749. 'h' => ' '.__('Hour'),
  750. 'i' => ' '.__('Minute'),
  751. 's' => ' '.__('Second'),
  752. );
  753. $p = array (
  754. 'm' => ' '.__('Months'), # translated
  755. 'd' => ' '.__('Days'),
  756. 'h' => ' '.__('Hours'),
  757. 'i' => ' '.__('Minutes'),
  758. 's' => ' '.__('Seconds'),
  759. );
  760. }
  761. if (!isset($format)) {
  762. //if (floor($seconds / MONTH) > 0) $format = "Md";
  763. if (floor($seconds / DAY) > 0) $format = "Dh";
  764. elseif (floor($seconds / 3600) > 0) $format = "Hi";
  765. elseif (floor($seconds / 60) > 0) $format = "Is";
  766. else $format = "S";
  767. }
  768. for ($i = 0; $i < mb_strlen($format); $i++) {
  769. switch (mb_substr($format, $i, 1)) {
  770. case 'D':
  771. $str = floor($seconds / 86400);
  772. break;
  773. case 'd':
  774. $str = floor($seconds / 86400 % 30);
  775. break;
  776. case 'H':
  777. $str = floor($seconds / 3600);
  778. break;
  779. case 'h':
  780. $str = floor($seconds / 3600 % 24);
  781. break;
  782. case 'I':
  783. $str = floor($seconds / 60);
  784. break;
  785. case 'i':
  786. $str = floor($seconds / 60 % 60);
  787. break;
  788. case 'S':
  789. $str = $seconds;
  790. break;
  791. case 's':
  792. $str = floor($seconds % 60);
  793. break;
  794. default:
  795. return "";
  796. break;
  797. }
  798. if ($str > 0 || $j > 0 || $options['zero'] || $i == mb_strlen($format) - 1) {
  799. if ($j>0) {
  800. $ret .= $options['separator'];
  801. }
  802. $j++;
  803. $x = mb_strtolower(mb_substr($format, $i, 1));
  804. if ($str == 1) {
  805. $ret .= $str . $s[$x];
  806. } else {
  807. $title = $p[$x];
  808. if (!empty($options['plural'])) {
  809. if (mb_substr($title, -1, 1) == 'e') {
  810. $title .= $options['plural'];
  811. }
  812. }
  813. $ret .= $str . $title;
  814. }
  815. }
  816. }
  817. return $ret;
  818. }
  819. /**
  820. * time relative to NOW in human readable format - absolute (negative as well as positive)
  821. * //TODO: make "now" adjustable
  822. * @param mixed $datestring
  823. * @param string format: format
  824. * @param options
  825. * - default, separator
  826. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  827. * - verbose/past/future: string with %s or boolean true/false
  828. * 2009-11-21 ms
  829. */
  830. public function relLengthOfTime($dateString, $format = null, $options = array()) {
  831. if ($dateString != null) {
  832. $userOffset = null;
  833. $sec = time() - $this->fromString($dateString, $userOffset);
  834. $type = ($sec > 0)?-1:(($sec < 0)?1:0);
  835. $sec = abs($sec);
  836. } else {
  837. $sec = 0;
  838. $type = 0;
  839. }
  840. $defaults = array('verbose'=>__('justNow'), 'zero'=>false,'separator'=>', ', 'future'=>__('In %s'), 'past'=>__('%s ago'),'default'=>'');
  841. $options = array_merge($defaults, $options);
  842. $ret = $this->lengthOfTime($sec, $format, $options);
  843. if ($type == 1) {
  844. if ($options['future'] !== false) {
  845. return sprintf($options['future'], $ret);
  846. }
  847. return array('future'=>$ret);
  848. } elseif ($type == -1) {
  849. if ($options['past'] !== false) {
  850. return sprintf($options['past'], $ret);
  851. }
  852. return array('past'=>$ret);
  853. } else {
  854. if ($options['verbose'] !== false) {
  855. return $options['verbose'];
  856. }
  857. //return array('now'=>true);
  858. }
  859. return $options['default'];
  860. }
  861. /**
  862. * Returns true if given datetime string was day before yesterday.
  863. *
  864. * @param string $dateString Datetime string or Unix timestamp
  865. * @param int $userOffset User's offset from GMT (in hours)
  866. * @return boolean True if datetime string was day before yesterday
  867. */
  868. public function wasDayBeforeYesterday($dateString, $userOffset = null) {
  869. $date = $this->fromString($dateString, $userOffset);
  870. return date(FORMAT_DB_DATE, $date) == date(FORMAT_DB_DATE, time()-2*DAY);
  871. }
  872. /**
  873. * Returns true if given datetime string is the day after tomorrow.
  874. *
  875. * @param string $dateString Datetime string or Unix timestamp
  876. * @param int $userOffset User's offset from GMT (in hours)
  877. * @return boolean True if datetime string is day after tomorrow
  878. */
  879. public function isDayAfterTomorrow($dateString, $userOffset = null) {
  880. $date = $this->fromString($dateString, $userOffset);
  881. return date(FORMAT_DB_DATE, $date) == date(FORMAT_DB_DATE, time()+2*DAY);
  882. }
  883. /**
  884. * Returns true if given datetime string is not today AND is in the future.
  885. *
  886. * @param string $dateString Datetime string or Unix timestamp
  887. * @param int $userOffset User's offset from GMT (in hours)
  888. * @return boolean True if datetime is not today AND is in the future
  889. */
  890. public function isNotTodayAndInTheFuture($dateString, $userOffset = null) {
  891. $date = $this->fromString($dateString, $userOffset);
  892. return date(FORMAT_DB_DATE, $date) > date(FORMAT_DB_DATE, time());
  893. }
  894. /**
  895. * Returns true if given datetime string is not now AND is in the future.
  896. *
  897. * @param string $dateString Datetime string or Unix timestamp
  898. * @param int $userOffset User's offset from GMT (in hours)
  899. * @return boolean True if datetime is not today AND is in the future
  900. */
  901. public function isInTheFuture($dateString, $userOffset = null) {
  902. $date = $this->fromString($dateString, $userOffset);
  903. return date(FORMAT_DB_DATETIME, $date) > date(FORMAT_DB_DATETIME, time());
  904. }
  905. /** CORE TIME HELPER **/
  906. /**
  907. * Converts a string representing the format for the function strftime and returns a
  908. * windows safe and i18n aware format.
  909. *
  910. * @param string $format Format with specifiers for strftime function.
  911. * Accepts the special specifier %S which mimics th modifier S for date()
  912. * @param string UNIX timestamp
  913. * @return string windows safe and date() function compatible format for strftime
  914. * @access public
  915. */
  916. public function convertSpecifiers($format, $time = null) {
  917. if (!$time) {
  918. $time = time();
  919. }
  920. $this->__time = $time;
  921. return preg_replace_callback('/\%(\w+)/', array($this, '__translateSpecifier'), $format);
  922. }
  923. /**
  924. * Auxiliary function to translate a matched specifier element from a regular expresion into
  925. * a windows safe and i18n aware specifier
  926. *
  927. * @param array $specifier match from regular expression
  928. * @return string converted element
  929. * @access private
  930. */
  931. public function __translateSpecifier($specifier) {
  932. switch ($specifier[1]) {
  933. case 'a':
  934. $abday = __c('abday', 5);
  935. if (is_array($abday)) {
  936. return $abday[date('w', $this->__time)];
  937. }
  938. break;
  939. case 'A':
  940. $day = __c('day',5);
  941. if (is_array($day)) {
  942. return $day[date('w', $this->__time)];
  943. }
  944. break;
  945. case 'c':
  946. $format = __c('d_t_fmt',5);
  947. if ($format != 'd_t_fmt') {
  948. return $this->convertSpecifiers($format, $this->__time);
  949. }
  950. break;
  951. case 'C':
  952. return sprintf("%02d", date('Y', $this->__time) / 100);
  953. case 'D':
  954. return '%m/%d/%y';
  955. case 'e':
  956. if (DS === '/') {
  957. return '%e';
  958. }
  959. $day = date('j', $this->__time);
  960. if ($day < 10) {
  961. $day = ' ' . $day;
  962. }
  963. return $day;
  964. case 'eS' :
  965. return date('jS', $this->__time);
  966. case 'b':
  967. case 'h':
  968. $months = __c('abmon', 5);
  969. if (is_array($months)) {
  970. return $months[date('n', $this->__time) -1];
  971. }
  972. return '%b';
  973. case 'B':
  974. $months = __c('mon',5);
  975. if (is_array($months)) {
  976. return $months[date('n', $this->__time) -1];
  977. }
  978. break;
  979. case 'n':
  980. return "\n";
  981. case 'p':
  982. case 'P':
  983. $default = array('am' => 0, 'pm' => 1);
  984. $meridiem = $default[date('a',$this->__time)];
  985. $format = __c('am_pm', 5);
  986. if (is_array($format)) {
  987. $meridiem = $format[$meridiem];
  988. return ($specifier[1] == 'P') ? strtolower($meridiem) : strtoupper($meridiem);
  989. }
  990. break;
  991. case 'r':
  992. $complete = __c('t_fmt_ampm', 5);
  993. if ($complete != 't_fmt_ampm') {
  994. return str_replace('%p',$this->__translateSpecifier(array('%p', 'p')),$complete);
  995. }
  996. break;
  997. case 'R':
  998. return date('H:i', $this->__time);
  999. case 't':
  1000. return "\t";
  1001. case 'T':
  1002. return '%H:%M:%S';
  1003. case 'u':
  1004. return ($weekDay = date('w', $this->__time)) ? $weekDay : 7;
  1005. case 'x':
  1006. $format = __c('d_fmt', 5);
  1007. if ($format != 'd_fmt') {
  1008. return $this->convertSpecifiers($format, $this->__time);
  1009. }
  1010. break;
  1011. case 'X':
  1012. $format = __c('t_fmt',5);
  1013. if ($format != 't_fmt') {
  1014. return $this->convertSpecifiers($format, $this->__time);
  1015. }
  1016. break;
  1017. }
  1018. return $specifier[0];
  1019. }
  1020. /**
  1021. * Converts given time (in server's time zone) to user's local time, given his/her offset from GMT.
  1022. *
  1023. * @param string $serverTime UNIX timestamp
  1024. * @param int $userOffset User's offset from GMT (in hours)
  1025. * @return string UNIX timestamp
  1026. * @access public
  1027. */
  1028. public function convert($serverTime, $userOffset) {
  1029. $serverOffset = $this->serverOffset();
  1030. $gmtTime = $serverTime - $serverOffset;
  1031. $userTime = $gmtTime + $userOffset * (60*60);
  1032. return $userTime;
  1033. }
  1034. /**
  1035. * Returns server's offset from GMT in seconds.
  1036. *
  1037. * @return int Offset
  1038. * @access public
  1039. */
  1040. public function serverOffset() {
  1041. return date('Z', time());
  1042. }
  1043. /**
  1044. * Returns a UNIX timestamp, given either a UNIX timestamp or a valid strtotime() date string.
  1045. *
  1046. * @param string $dateString Datetime string
  1047. * @param int $userOffset User's offset from GMT (in hours)
  1048. * @return string Parsed timestamp
  1049. * @access public
  1050. * @link http://book.cakephp.org/view/1471/Formatting
  1051. */
  1052. public function fromString($dateString, $userOffset = null) {
  1053. if (empty($dateString)) {
  1054. return false;
  1055. }
  1056. if (is_integer($dateString) || is_numeric($dateString)) {
  1057. $date = intval($dateString);
  1058. } else {
  1059. $date = strtotime($dateString);
  1060. }
  1061. if ($userOffset !== null) {
  1062. return $this->convert($date, $userOffset);
  1063. }
  1064. if ($date === -1) {
  1065. return false;
  1066. }
  1067. return $date;
  1068. }
  1069. /**
  1070. * Returns a nicely formatted date string for given Datetime string.
  1071. *
  1072. * @param string $dateString Datetime string or Unix timestamp
  1073. * @param int $userOffset User's offset from GMT (in hours)
  1074. * @return string Formatted date string
  1075. * @access public
  1076. * @link http://book.cakephp.org/view/1471/Formatting
  1077. */
  1078. public function nice($dateString = null, $userOffset = null) {
  1079. if ($dateString != null) {
  1080. $date = $this->fromString($dateString, $userOffset);
  1081. } else {
  1082. $date = time();
  1083. }
  1084. $format = $this->convertSpecifiers('%a, %b %eS %Y, %H:%M', $date);
  1085. return strftime($format, $date);
  1086. }
  1087. /**
  1088. * Returns a formatted descriptive date string for given datetime string.
  1089. *
  1090. * If the given date is today, the returned string could be "Today, 16:54".
  1091. * If the given date was yesterday, the returned string could be "Yesterday, 16:54".
  1092. * If $dateString's year is the current year, the returned string does not
  1093. * include mention of the year.
  1094. *
  1095. * @param string $dateString Datetime string or Unix timestamp
  1096. * @param int $userOffset User's offset from GMT (in hours)
  1097. * @return string Described, relative date string
  1098. * @access public
  1099. * @link http://book.cakephp.org/view/1471/Formatting
  1100. */
  1101. public function niceShort($dateString = null, $userOffset = null) {
  1102. $date = $dateString ? $this->fromString($dateString, $userOffset) : time();
  1103. $y = $this->isThisYear($date) ? '' : ' %Y';
  1104. if ($this->isToday($dateString, $userOffset)) {
  1105. $ret = __('Today, %s', strftime("%H:%M", $date));
  1106. } elseif ($this->wasYesterday($dateString, $userOffset)) {
  1107. $ret = __('Yesterday, %s', strftime("%H:%M", $date));
  1108. } else {
  1109. $format = $this->convertSpecifiers("%b %eS{$y}, %H:%M", $date);
  1110. $ret = strftime($format, $date);
  1111. }
  1112. return $ret;
  1113. }
  1114. /**
  1115. * Returns a partial SQL string to search for all records between two dates.
  1116. *
  1117. * @param string $dateString Datetime string or Unix timestamp
  1118. * @param string $end Datetime string or Unix timestamp
  1119. * @param string $fieldName Name of database field to compare with
  1120. * @param int $userOffset User's offset from GMT (in hours)
  1121. * @return string Partial SQL string.
  1122. * @access public
  1123. * @link http://book.cakephp.org/view/1471/Formatting
  1124. */
  1125. public function daysAsSql($begin, $end, $fieldName, $userOffset = null) {
  1126. $begin = $this->fromString($begin, $userOffset);
  1127. $end = $this->fromString($end, $userOffset);
  1128. $begin = date('Y-m-d', $begin) . ' 00:00:00';
  1129. $end = date('Y-m-d', $end) . ' 23:59:59';
  1130. return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
  1131. }
  1132. /**
  1133. * Returns a partial SQL string to search for all records between two times
  1134. * occurring on the same day.
  1135. *
  1136. * @param string $dateString Datetime string or Unix timestamp
  1137. * @param string $fieldName Name of database field to compare with
  1138. * @param int $userOffset User's offset from GMT (in hours)
  1139. * @return string Partial SQL string.
  1140. * @access public
  1141. * @link http://book.cakephp.org/view/1471/Formatting
  1142. */
  1143. public function dayAsSql($dateString, $fieldName, $userOffset = null) {
  1144. $date = $this->fromString($dateString, $userOffset);
  1145. return $this->daysAsSql($dateString, $dateString, $fieldName);
  1146. }
  1147. /**
  1148. * try to parse date from various input formats
  1149. * - DD.MM.YYYY, DD/MM/YYYY, YYYY-MM-DD, YYYY, YYYY-MM, ...
  1150. * - i18n: Today, Yesterday, Tomorrow
  1151. * @param string $date to parse
  1152. * @param format to parse (null = auto)
  1153. * @param type
  1154. * - start: first second of this interval
  1155. * - end: last second of this interval
  1156. * @return int timestamp
  1157. * 2011-11-19 ms
  1158. */
  1159. public function parseDate($date, $format = null, $type = 'start') {
  1160. $date = trim($date);
  1161. $i18n = array(
  1162. strtolower(__('Today')) => array('start'=>date(FORMAT_DB_DATETIME, mktime(0, 0, 0, date('m'), date('d'), date('Y'))), 'end'=>date(FORMAT_DB_DATETIME, mktime(23, 59, 59, date('m'), date('d'), date('Y')))),
  1163. strtolower(__('Tomorrow')) => array('start'=>date(FORMAT_DB_DATETIME, mktime(0, 0, 0, date('m'), date('d'), date('Y'))+DAY), 'end'=>date(FORMAT_DB_DATETIME, mktime(23, 59, 59, date('m'), date('d'), date('Y'))+DAY)),
  1164. strtolower(__('Yesterday')) => array('start'=>date(FORMAT_DB_DATETIME, mktime(0, 0, 0, date('m'), date('d'), date('Y'))-DAY), 'end'=>date(FORMAT_DB_DATETIME, mktime(23, 59, 59, date('m'), date('d'), date('Y'))-DAY)),
  1165. strtolower(__('The day after tomorrow')) => array('start'=>date(FORMAT_DB_DATETIME, mktime(0, 0, 0, date('m'), date('d'), date('Y'))+2*DAY), 'end'=>date(FORMAT_DB_DATETIME, mktime(23, 59, 59, date('m'), date('d'), date('Y'))*2*DAY)),
  1166. strtolower(__('The day before yesterday')) => array('start'=>date(FORMAT_DB_DATETIME, mktime(0, 0, 0, date('m'), date('d'), date('Y'))-2*DAY), 'end'=>date(FORMAT_DB_DATETIME, mktime(23, 59, 59, date('m'), date('d'), date('Y'))-2*DAY)),
  1167. );
  1168. if (isset($i18n[strtolower($date)])) {
  1169. return $i18n[strtolower($date)][$type];
  1170. }
  1171. if ($format) {
  1172. $res = DateTime::createFromFormat($format, $date);
  1173. $res = $res->format(FORMAT_DB_DATE).' '.($type=='end'?'23:59:59':'00:00:00');
  1174. return $res;
  1175. }
  1176. if (strpos($date, '.') !== false) {
  1177. $explode = explode('.', $date, 3);
  1178. $explode = array_reverse($explode);
  1179. } elseif (strpos($date, '/') !== false) {
  1180. $explode = explode('/', $date, 3);
  1181. $explode = array_reverse($explode);
  1182. } elseif (strpos($date, '-') !== false) {
  1183. $explode = explode('-', $date, 3);
  1184. } else {
  1185. $explode = array($date);
  1186. }
  1187. if (isset($explode)) {
  1188. for ($i = 0; $i < count($explode); $i++) {
  1189. $explode[$i] = str_pad($explode[$i], 2, '0', STR_PAD_LEFT);
  1190. }
  1191. $explode[0] = str_pad($explode[0], 4, '20', STR_PAD_LEFT);
  1192. if (count($explode) === 3) {
  1193. return implode('-', $explode).' '.($type=='end'?'23:59:59':'00:00:00');
  1194. } elseif (count($explode) === 2) {
  1195. return implode('-', $explode).'-'.($type=='end'?$this->daysInMonth($explode[0], $explode[1]):'01').' '.($type=='end'?'23:59:59':'00:00:00');
  1196. } else {
  1197. return $explode[0].'-'.($type=='end'?'12':'01').'-'.($type=='end'?'31':'01').' '.($type=='end'?'23:59:59':'00:00:00');
  1198. }
  1199. }
  1200. return false;
  1201. }
  1202. /**
  1203. * @param string $searchString to parse
  1204. * @param array $options
  1205. * - separator (defaults to space [ ])
  1206. * - format (defaults to Y-m-d H:i:s)
  1207. * @return array $period [0=>min, 1=>max]
  1208. * 2011-11-18 ms
  1209. */
  1210. public function period($string, $options = array()) {
  1211. if (strpos($string, ' ') !== false) {
  1212. $filters = explode(' ', $string);
  1213. $filters = array(array_shift($filters), array_pop($filters));
  1214. } else {
  1215. $filters = array($string, $string);
  1216. }
  1217. $min = $filters[0];
  1218. $max = $filters[1];
  1219. //$x = preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', $date, $date_parts);
  1220. //$x = Datetime::createFromFormat('Y-m-d', $string);
  1221. //die(returns($x));
  1222. //$actualDateTime = new DateTime($min);
  1223. //$actualDateTime->add(new DateInterval('P1M'));
  1224. $min = $this->parseDate($min);
  1225. $max = $this->parseDate($max, null, 'end');
  1226. //die($actualDateTime->format('Y-m-d'));
  1227. //$searchParameters['conditions']['Coupon.date'] = $actualDateTime->format('Y-m-d');
  1228. /*
  1229. if ($min == $max) {
  1230. if (strlen($max) > 8) {
  1231. $max = date(FORMAT_DB_DATE, strtotime($max)+DAY);
  1232. } elseif (strlen($max) > 5) {
  1233. $max = date(FORMAT_DB_DATE, strtotime($max)+MONTH);
  1234. } else {
  1235. $max = date(FORMAT_DB_DATE, strtotime($max)+YEAR+MONTH);
  1236. }
  1237. }
  1238. $min = date(FORMAT_DB_DATE, strtotime($min));
  1239. $max = date(FORMAT_DB_DATE, strtotime($max));
  1240. */
  1241. return array($min, $max);
  1242. }
  1243. /**
  1244. * @param string $searchString to parse
  1245. * @param string $fieldname (Model.field)
  1246. * @param array $options (see DatetimeLib::period)
  1247. * @return string $query SQL Query
  1248. * 2011-11-18 ms
  1249. */
  1250. public function periodAsSql($string, $fieldName, $options = array()) {
  1251. $period = $this->period($string, $options);
  1252. return $this->daysAsSql($period[0], $period[1], $fieldName);
  1253. }
  1254. /**
  1255. * Returns true if given datetime string is today.
  1256. *
  1257. * @param string $dateString Datetime string or Unix timestamp
  1258. * @param int $userOffset User's offset from GMT (in hours)
  1259. * @return boolean True if datetime string is today
  1260. * @access public
  1261. */
  1262. public function isToday($dateString, $userOffset = null) {
  1263. $date = $this->fromString($dateString, $userOffset);
  1264. return date('Y-m-d', $date) == date('Y-m-d', time());
  1265. }
  1266. /**
  1267. * Returns true if given datetime string is within this week
  1268. * @param string $dateString
  1269. * @param int $userOffset User's offset from GMT (in hours)
  1270. * @return boolean True if datetime string is within current week
  1271. * @access public
  1272. * @link http://book.cakephp.org/view/1472/Testing-Time
  1273. */
  1274. public function isThisWeek($dateString, $userOffset = null) {
  1275. $date = $this->fromString($dateString, $userOffset);
  1276. return date('W Y', $date) == date('W Y', time());
  1277. }
  1278. /**
  1279. * Returns true if given datetime string is within this month
  1280. * @param string $dateString
  1281. * @param int $userOffset User's offset from GMT (in hours)
  1282. * @return boolean True if datetime string is within current month
  1283. * @access public
  1284. * @link http://book.cakephp.org/view/1472/Testing-Time
  1285. */
  1286. public function isThisMonth($dateString, $userOffset = null) {
  1287. $date = $this->fromString($dateString);
  1288. return date('m Y',$date) == date('m Y', time());
  1289. }
  1290. /**
  1291. * Returns true if given datetime string is within current year.
  1292. *
  1293. * @param string $dateString Datetime string or Unix timestamp
  1294. * @return boolean True if datetime string is within current year
  1295. * @access public
  1296. * @link http://book.cakephp.org/view/1472/Testing-Time
  1297. */
  1298. public function isThisYear($dateString, $userOffset = null) {
  1299. $date = $this->fromString($dateString, $userOffset);
  1300. return date('Y', $date) == date('Y', time());
  1301. }
  1302. /**
  1303. * Returns true if given datetime string was yesterday.
  1304. *
  1305. * @param string $dateString Datetime string or Unix timestamp
  1306. * @param int $userOffset User's offset from GMT (in hours)
  1307. * @return boolean True if datetime string was yesterday
  1308. * @access public
  1309. * @link http://book.cakephp.org/view/1472/Testing-Time
  1310. *
  1311. */
  1312. public function wasYesterday($dateString, $userOffset = null) {
  1313. $date = $this->fromString($dateString, $userOffset);
  1314. return date('Y-m-d', $date) == date('Y-m-d', strtotime('yesterday'));
  1315. }
  1316. /**
  1317. * Returns true if given datetime string is tomorrow.
  1318. *
  1319. * @param string $dateString Datetime string or Unix timestamp
  1320. * @param int $userOffset User's offset from GMT (in hours)
  1321. * @return boolean True if datetime string was yesterday
  1322. * @access public
  1323. * @link http://book.cakephp.org/view/1472/Testing-Time
  1324. */
  1325. public function isTomorrow($dateString, $userOffset = null) {
  1326. $date = $this->fromString($dateString, $userOffset);
  1327. return date('Y-m-d', $date) == date('Y-m-d', strtotime('tomorrow'));
  1328. }
  1329. /**
  1330. * Returns the quarter
  1331. *
  1332. * @param string $dateString
  1333. * @param boolean $range if true returns a range in Y-m-d format
  1334. * @return boolean True if datetime string is within current week
  1335. * @access public
  1336. * @link http://book.cakephp.org/view/1471/Formatting
  1337. */
  1338. public function toQuarter($dateString, $range = false) {
  1339. $time = $this->fromString($dateString);
  1340. $date = ceil(date('m', $time) / 3);
  1341. if ($range === true) {
  1342. $range = 'Y-m-d';
  1343. }
  1344. if ($range !== false) {
  1345. $year = date('Y', $time);
  1346. switch ($date) {
  1347. case 1:
  1348. $date = array($year.'-01-01', $year.'-03-31');
  1349. break;
  1350. case 2:
  1351. $date = array($year.'-04-01', $year.'-06-30');
  1352. break;
  1353. case 3:
  1354. $date = array($year.'-07-01', $year.'-09-30');
  1355. break;
  1356. case 4:
  1357. $date = array($year.'-10-01', $year.'-12-31');
  1358. break;
  1359. }
  1360. }
  1361. return $date;
  1362. }
  1363. /**
  1364. * Returns a UNIX timestamp from a textual datetime description. Wrapper for PHP function strtotime().
  1365. *
  1366. * @param string $dateString Datetime string to be represented as a Unix timestamp
  1367. * @param int $userOffset User's offset from GMT (in hours)
  1368. * @return integer Unix timestamp
  1369. * @access public
  1370. * @link http://book.cakephp.org/view/1471/Formatting
  1371. */
  1372. public function toUnix($dateString, $userOffset = null) {
  1373. return $this->fromString($dateString, $userOffset);
  1374. }
  1375. /**
  1376. * Returns a date formatted for Atom RSS feeds.
  1377. *
  1378. * @param string $dateString Datetime string or Unix timestamp
  1379. * @param int $userOffset User's offset from GMT (in hours)
  1380. * @return string Formatted date string
  1381. * @access public
  1382. * @link http://book.cakephp.org/view/1471/Formatting
  1383. */
  1384. public function toAtom($dateString, $userOffset = null) {
  1385. $date = $this->fromString($dateString, $userOffset);
  1386. return date('Y-m-d\TH:i:s\Z', $date);
  1387. }
  1388. /**
  1389. * Formats date for RSS feeds
  1390. *
  1391. * @param string $dateString Datetime string or Unix timestamp
  1392. * @param int $userOffset User's offset from GMT (in hours)
  1393. * @return string Formatted date string
  1394. * @access public
  1395. * @link http://book.cakephp.org/view/1471/Formatting
  1396. */
  1397. public function toRSS($dateString, $userOffset = null) {
  1398. $date = $this->fromString($dateString, $userOffset);
  1399. return date("r", $date);
  1400. }
  1401. /**
  1402. * Returns either a relative date or a formatted date depending
  1403. * on the difference between the current time and given datetime.
  1404. * $datetime should be in a <i>strtotime</i> - parsable format, like MySQL's datetime datatype.
  1405. *
  1406. * ### Options:
  1407. *
  1408. * - `format` => a fall back format if the relative time is longer than the duration specified by end
  1409. * - `end` => The end of relative time telling
  1410. * - `userOffset` => Users offset from GMT (in hours)
  1411. *
  1412. * Relative dates look something like this:
  1413. * 3 weeks, 4 days ago
  1414. * 15 seconds ago
  1415. *
  1416. * Default date formatting is d/m/yy e.g: on 18/2/09
  1417. *
  1418. * The returned string includes 'ago' or 'on' and assumes you'll properly add a word
  1419. * like 'Posted ' before the function output.
  1420. *
  1421. * @param string $dateString Datetime string or Unix timestamp
  1422. * @param array $options Default format if timestamp is used in $dateString
  1423. * @return string Relative time string.
  1424. * @access public
  1425. * @link http://book.cakephp.org/view/1471/Formatting
  1426. */
  1427. public function timeAgoInWords($dateTime, $options = array()) {
  1428. $userOffset = null;
  1429. if (is_array($options) && isset($options['userOffset'])) {
  1430. $userOffset = $options['userOffset'];
  1431. }
  1432. $now = time();
  1433. if (!is_null($userOffset)) {
  1434. $now = $this->convert(time(), $userOffset);
  1435. }
  1436. $inSeconds = $this->fromString($dateTime, $userOffset);
  1437. $backwards = ($inSeconds > $now);
  1438. $format = 'j/n/y';
  1439. $end = '+1 month';
  1440. if (is_array($options)) {
  1441. if (isset($options['format'])) {
  1442. $format = $options['format'];
  1443. unset($options['format']);
  1444. }
  1445. if (isset($options['end'])) {
  1446. $end = $options['end'];
  1447. unset($options['end']);
  1448. }
  1449. } else {
  1450. $format = $options;
  1451. }
  1452. if ($backwards) {
  1453. $futureTime = $inSeconds;
  1454. $pastTime = $now;
  1455. } else {
  1456. $futureTime = $now;
  1457. $pastTime = $inSeconds;
  1458. }
  1459. $diff = $futureTime - $pastTime;
  1460. // If more than a week, then take into account the length of months
  1461. if ($diff >= 604800) {
  1462. $current = array();
  1463. $date = array();
  1464. list($future['H'], $future['i'], $future['s'], $future['d'], $future['m'], $future['Y']) = explode('/', date('H/i/s/d/m/Y', $futureTime));
  1465. list($past['H'], $past['i'], $past['s'], $past['d'], $past['m'], $past['Y']) = explode('/', date('H/i/s/d/m/Y', $pastTime));
  1466. $years = $months = $weeks = $days = $hours = $minutes = $seconds = 0;
  1467. if ($future['Y'] == $past['Y'] && $future['m'] == $past['m']) {
  1468. $months = 0;
  1469. $years = 0;
  1470. } else {
  1471. if ($future['Y'] == $past['Y']) {
  1472. $months = $future['m'] - $past['m'];
  1473. } else {
  1474. $years = $future['Y'] - $past['Y'];
  1475. $months = $future['m'] + ((12 * $years) - $past['m']);
  1476. if ($months >= 12) {
  1477. $years = floor($months / 12);
  1478. $months = $months - ($years * 12);
  1479. }
  1480. if ($future['m'] < $past['m'] && $future['Y'] - $past['Y'] == 1) {
  1481. $years --;
  1482. }
  1483. }
  1484. }
  1485. if ($future['d'] >= $past['d']) {
  1486. $days = $future['d'] - $past['d'];
  1487. } else {
  1488. $daysInPastMonth = date('t', $pastTime);
  1489. $daysInFutureMonth = date('t', mktime(0, 0, 0, $future['m'] - 1, 1, $future['Y']));
  1490. if (!$backwards) {
  1491. $days = ($daysInPastMonth - $past['d']) + $future['d'];
  1492. } else {
  1493. $days = ($daysInFutureMonth - $past['d']) + $future['d'];
  1494. }
  1495. if ($future['m'] != $past['m']) {
  1496. $months --;
  1497. }
  1498. }
  1499. if ($months == 0 && $years >= 1 && $diff < ($years * 31536000)) {
  1500. $months = 11;
  1501. $years --;
  1502. }
  1503. if ($months >= 12) {
  1504. $years = $years + 1;
  1505. $months = $months - 12;
  1506. }
  1507. if ($days >= 7) {
  1508. $weeks = floor($days / 7);
  1509. $days = $days - ($weeks * 7);
  1510. }
  1511. } else {
  1512. $years = $months = $weeks = 0;
  1513. $days = floor($diff / 86400);
  1514. $diff = $diff - ($days * 86400);
  1515. $hours = floor($diff / 3600);
  1516. $diff = $diff - ($hours * 3600);
  1517. $minutes = floor($diff / 60);
  1518. $diff = $diff - ($minutes * 60);
  1519. $seconds = $diff;
  1520. }
  1521. $relativeDate = '';
  1522. $diff = $futureTime - $pastTime;
  1523. if ($diff > abs($now - $this->fromString($end))) {
  1524. $relativeDate = __('on %s', date($format, $inSeconds));
  1525. } else {
  1526. if ($years > 0) {
  1527. // years and months and days
  1528. $relativeDate .= ($relativeDate ? ', ' : '') . $years . ' ' . __n('year', 'years', $years);
  1529. $relativeDate .= $months > 0 ? ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months) : '';
  1530. $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks) : '';
  1531. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days) : '';
  1532. } elseif (abs($months) > 0) {
  1533. // months, weeks and days
  1534. $relativeDate .= ($relativeDate ? ', ' : '') . $months . ' ' . __n('month', 'months', $months);
  1535. $relativeDate .= $weeks > 0 ? ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks) : '';
  1536. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days) : '';
  1537. } elseif (abs($weeks) > 0) {
  1538. // weeks and days
  1539. $relativeDate .= ($relativeDate ? ', ' : '') . $weeks . ' ' . __n('week', 'weeks', $weeks);
  1540. $relativeDate .= $days > 0 ? ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days) : '';
  1541. } elseif (abs($days) > 0) {
  1542. // days and hours
  1543. $relativeDate .= ($relativeDate ? ', ' : '') . $days . ' ' . __n('day', 'days', $days);
  1544. $relativeDate .= $hours > 0 ? ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours) : '';
  1545. } elseif (abs($hours) > 0) {
  1546. // hours and minutes
  1547. $relativeDate .= ($relativeDate ? ', ' : '') . $hours . ' ' . __n('hour', 'hours', $hours);
  1548. $relativeDate .= $minutes > 0 ? ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes) : '';
  1549. } elseif (abs($minutes) > 0) {
  1550. // minutes only
  1551. $relativeDate .= ($relativeDate ? ', ' : '') . $minutes . ' ' . __n('minute', 'minutes', $minutes);
  1552. } else {
  1553. // seconds only
  1554. $relativeDate .= ($relativeDate ? ', ' : '') . $seconds . ' ' . __n('second', 'seconds', $seconds);
  1555. }
  1556. if (!$backwards) {
  1557. $relativeDate = __('%s ago', $relativeDate);
  1558. }
  1559. }
  1560. return $relativeDate;
  1561. }
  1562. /**
  1563. * Alias for timeAgoInWords
  1564. *
  1565. * @param mixed $dateTime Datetime string (strtotime-compatible) or Unix timestamp
  1566. * @param mixed $options Default format string, if timestamp is used in $dateTime, or an array of options to be passed
  1567. * on to timeAgoInWords().
  1568. * @return string Relative time string.
  1569. * @see TimeHelper::timeAgoInWords
  1570. * @access public
  1571. * @deprecated This method alias will be removed in future versions.
  1572. * @link http://book.cakephp.org/view/1471/Formatting
  1573. */
  1574. public function relativeTime($dateTime, $options = array()) {
  1575. return $this->timeAgoInWords($dateTime, $options);
  1576. }
  1577. /**
  1578. * Returns true if specified datetime was within the interval specified, else false.
  1579. *
  1580. * @param mixed $timeInterval the numeric value with space then time type.
  1581. * Example of valid types: 6 hours, 2 days, 1 minute.
  1582. * @param mixed $dateString the datestring or unix timestamp to compare
  1583. * @param int $userOffset User's offset from GMT (in hours)
  1584. * @return bool
  1585. * @access public
  1586. * @link http://book.cakephp.org/view/1472/Testing-Time
  1587. */
  1588. public function wasWithinLast($timeInterval, $dateString, $userOffset = null) {
  1589. $tmp = str_replace(' ', '', $timeInterval);
  1590. if (is_numeric($tmp)) {
  1591. $timeInterval = $tmp . ' ' . __('days');
  1592. }
  1593. $date = $this->fromString($dateString, $userOffset);
  1594. $interval = $this->fromString('-'.$timeInterval);
  1595. if ($date >= $interval && $date <= time()) {
  1596. return true;
  1597. }
  1598. return false;
  1599. }
  1600. /**
  1601. * Returns gmt, given either a UNIX timestamp or a valid strtotime() date string.
  1602. *
  1603. * @param string $dateString Datetime string
  1604. * @return string Formatted date string
  1605. * @access public
  1606. * @link http://book.cakephp.org/view/1471/Formatting
  1607. */
  1608. public function gmt($string = null) {
  1609. if ($string != null) {
  1610. $string = $this->fromString($string);
  1611. } else {
  1612. $string = time();
  1613. }
  1614. $string = $this->fromString($string);
  1615. $hour = intval(date("G", $string));
  1616. $minute = intval(date("i", $string));
  1617. $second = intval(date("s", $string));
  1618. $month = intval(date("n", $string));
  1619. $day = intval(date("j", $string));
  1620. $year = intval(date("Y", $string));
  1621. return gmmktime($hour, $minute, $second, $month, $day, $year);
  1622. }
  1623. /**
  1624. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  1625. * This function also accepts a time string and a format string as first and second parameters.
  1626. * In that case this function behaves as a wrapper for TimeHelper::i18nFormat()
  1627. *
  1628. * @param string $format date format string (or a DateTime string)
  1629. * @param string $dateString Datetime string (or a date format string)
  1630. * @param boolean $invalid flag to ignore results of fromString == false
  1631. * @param int $userOffset User's offset from GMT (in hours)
  1632. * @return string Formatted date string
  1633. * @access public
  1634. */
  1635. public function format($format, $date = null, $invalid = false, $userOffset = null) {
  1636. $time = $this->fromString($date, $userOffset);
  1637. $_time = $this->fromString($format, $userOffset);
  1638. if (is_numeric($_time) && $time === false) {
  1639. $format = $date;
  1640. return $this->i18nFormat($_time, $format, $invalid, $userOffset);
  1641. }
  1642. if ($time === false && $invalid !== false) {
  1643. return $invalid;
  1644. }
  1645. return date($format, $time);
  1646. }
  1647. /**
  1648. * Returns a formatted date string, given either a UNIX timestamp or a valid strtotime() date string.
  1649. * It take in account the default date format for the current language if a LC_TIME file is used.
  1650. *
  1651. * @param string $dateString Datetime string
  1652. * @param string $format strftime format string.
  1653. * @param boolean $invalid flag to ignore results of fromString == false
  1654. * @param int $userOffset User's offset from GMT (in hours)
  1655. * @return string Formatted and translated date string @access public
  1656. * @access public
  1657. */
  1658. public function i18nFormat($date, $format = null, $invalid = false, $userOffset = null) {
  1659. $date = $this->fromString($date, $userOffset);
  1660. if ($date === false && $invalid !== false) {
  1661. return $invalid;
  1662. }
  1663. if (empty($format)) {
  1664. $format = '%x';
  1665. }
  1666. $format = $this->convertSpecifiers($format, $date);
  1667. return strftime($format, $date);
  1668. }
  1669. }