FrozenTime.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422
  1. <?php
  2. namespace Tools\Utility;
  3. use Cake\Chronos\Date;
  4. use Cake\Chronos\MutableDate;
  5. use Cake\Core\Configure;
  6. use Cake\I18n\FrozenDate;
  7. use Cake\I18n\FrozenTime as CakeFrozenTime;
  8. use DateInterval;
  9. use DateTime;
  10. use DateTimeInterface;
  11. use DateTimeZone;
  12. use IntlDateFormatter;
  13. /**
  14. * Extend CakeTime with a few important improvements:
  15. * - correct timezones for date only input and therefore unchanged day here
  16. */
  17. class FrozenTime extends CakeFrozenTime {
  18. /**
  19. * @param \DateTimeInterface|array|string|int|null $time Fixed or relative time
  20. * @param \DateTimeZone|string|null $tz The timezone for the instance
  21. */
  22. public function __construct($time = null, $tz = null) {
  23. if (is_array($time)) {
  24. $value = $time + ['hour' => 0, 'minute' => 0, 'second' => 0];
  25. $format = '';
  26. if (
  27. isset($value['year'], $value['month'], $value['day']) &&
  28. (is_numeric($value['year']) && is_numeric($value['month']) && is_numeric($value['day']))
  29. ) {
  30. $format .= sprintf('%d-%02d-%02d', $value['year'], $value['month'], $value['day']);
  31. }
  32. if (isset($value['meridian'])) {
  33. $value['hour'] = strtolower($value['meridian']) === 'am' ? $value['hour'] : $value['hour'] + 12;
  34. }
  35. $format .= sprintf(
  36. '%s%02d:%02d:%02d',
  37. empty($format) ? '' : ' ',
  38. $value['hour'],
  39. $value['minute'],
  40. $value['second'],
  41. );
  42. $time = $format;
  43. }
  44. parent::__construct($time, $tz);
  45. }
  46. /**
  47. * Detect if a timezone has a DST
  48. *
  49. * @param \DateTimeZone|string|null $timezone User's timezone string or DateTimeZone object
  50. * @return bool
  51. */
  52. public function hasDaylightSavingTime($timezone = null) {
  53. $timezone = $this->safeCreateDateTimeZone($timezone);
  54. // a date outside of DST
  55. $offset = $timezone->getOffset(new CakeFrozenTime('@' . mktime(0, 0, 0, 2, 1, (int)date('Y'))));
  56. $offset = $offset / HOUR;
  57. // a date inside of DST
  58. $offset2 = $timezone->getOffset(new CakeFrozenTime('@' . mktime(0, 0, 0, 8, 1, (int)date('Y'))));
  59. $offset2 = $offset2 / HOUR;
  60. return abs($offset2 - $offset) > 0;
  61. }
  62. /**
  63. * Calculate the difference between two dates
  64. *
  65. * TODO: deprecate in favor of DateTime::diff() etc which will be more precise
  66. *
  67. * should only be used for < month (due to the different month lenghts it gets fuzzy)
  68. *
  69. * @param mixed $startTime (db format or timestamp)
  70. * @param mixed|null $endTime (db format or timestamp)
  71. * @param array<string, mixed> $options
  72. * @return int The distance in seconds
  73. */
  74. public static function difference($startTime, $endTime = null, array $options = []) {
  75. if (!is_int($startTime)) {
  76. $startTime = strtotime($startTime);
  77. }
  78. if (!is_int($endTime)) {
  79. $endTime = strtotime($endTime);
  80. }
  81. //@FIXME: make it work for > month
  82. return abs($endTime - $startTime);
  83. }
  84. /**
  85. * Calculates the age using start and optional end date.
  86. * Both dates default to current date. Note that start needs
  87. * to be before end for a valid result.
  88. *
  89. * @param \DateTimeInterface|string|int $start Start date (if empty, use today)
  90. * @param \DateTimeInterface|string|int|null $end End date (if empty, use today)
  91. * @return int Age (0 if both timestamps are equal or empty, -1 on invalid dates)
  92. */
  93. public static function age($start, $end = null) {
  94. if (!$start && !$end || $start == $end) {
  95. return 0;
  96. }
  97. if (is_int($start)) {
  98. $start = date(FORMAT_DB_DATE, $start);
  99. }
  100. if (is_int($end)) {
  101. $end = date(FORMAT_DB_DATE, $end);
  102. }
  103. $startDate = $start;
  104. if (!is_object($start)) {
  105. $startDate = new CakeFrozenTime($start);
  106. }
  107. $endDate = $end;
  108. if (!is_object($end)) {
  109. $endDate = new CakeFrozenTime($end);
  110. }
  111. if ($startDate > $endDate) {
  112. return -1;
  113. }
  114. $oDateInterval = $endDate->diff($startDate);
  115. return $oDateInterval->y;
  116. }
  117. /**
  118. * Returns the age only with the year available
  119. * can be e.g. 22/23
  120. *
  121. * @param int $year
  122. * @param int|null $month (optional)
  123. * @return string|int Age
  124. */
  125. public static function ageByYear($year, $month = null) {
  126. if ($month === null) {
  127. $maxAge = static::age(mktime(0, 0, 0, 1, 1, $year));
  128. $minAge = static::age(mktime(23, 59, 59, 12, 31, $year));
  129. $ages = array_unique([$minAge, $maxAge]);
  130. return implode('/', $ages);
  131. }
  132. if ((int)date('n') === $month) {
  133. $maxAge = static::age(mktime(0, 0, 0, $month, 1, $year));
  134. $minAge = static::age(mktime(23, 59, 59, $month, static::daysInMonth($year, $month), $year));
  135. $ages = array_unique([$minAge, $maxAge]);
  136. return implode('/', $ages);
  137. }
  138. return static::age(mktime(0, 0, 0, $month, 1, $year));
  139. }
  140. /**
  141. * Rounded age depended on steps (e.g. age 16 with steps = 10 => "11-20")
  142. * //FIXME
  143. * //TODO: move to helper?
  144. *
  145. * @param int $year
  146. * @param int|null $month
  147. * @param int|null $day
  148. * @param int $steps
  149. * @return mixed
  150. */
  151. public static function ageRange($year, $month = null, $day = null, $steps = 1) {
  152. if ($month == null && $day == null) {
  153. $age = (int)date('Y') - $year - 1;
  154. } elseif ($day == null) {
  155. if ($month >= (int)date('m')) {
  156. $age = (int)date('Y') - $year - 1;
  157. } else {
  158. $age = (int)date('Y') - $year;
  159. }
  160. } else {
  161. if ($month > (int)date('m') || ($month == (int)date('m') && $day > (int)date('d'))) {
  162. $age = (int)date('Y') - $year - 1;
  163. } else {
  164. $age = (int)date('Y') - $year;
  165. }
  166. }
  167. if ($age % $steps == 0) {
  168. $lowerRange = $age - $steps + 1;
  169. $upperRange = $age;
  170. } else {
  171. $lowerRange = $age - ($age % $steps) + 1;
  172. $upperRange = $age - ($age % $steps) + $steps;
  173. }
  174. if ($lowerRange == $upperRange) {
  175. return $upperRange;
  176. }
  177. return [$lowerRange, $upperRange];
  178. }
  179. /**
  180. * Return the days of a given month.
  181. *
  182. * @param int $year
  183. * @param int $month
  184. * @return int Days
  185. */
  186. public static function daysInMonth($year, $month) {
  187. return (int)date('t', mktime(0, 0, 0, $month, 1, $year));
  188. }
  189. /**
  190. * Calendar Week (current week of the year).
  191. * //TODO: use timestamp - or make the function able to use timestamps at least (besides dateString)
  192. *
  193. * date('W', $time) returns ISO6801 week number.
  194. * Exception: Dates of the calender week of the previous year return 0. In this case the cweek of the
  195. * last week of the previous year should be used.
  196. *
  197. * @param mixed|null $dateString In DB format - if none is passed, current day is used
  198. * @param int $relative - weeks relative to the date (+1 next, -1 previous etc)
  199. * @return string
  200. */
  201. public static function cWeek($dateString = null, $relative = 0) {
  202. if ($dateString) {
  203. $date = explode(' ', $dateString);
  204. [$y, $m, $d] = explode('-', $date[0]);
  205. $t = mktime(0, 0, 0, (int)$m, (int)$d, (int)$y);
  206. } else {
  207. $y = date('Y');
  208. $t = time();
  209. }
  210. $relative = (int)$relative;
  211. if ($relative !== 0) {
  212. $t += WEEK * $relative; // 1day * 7 * relativeWeeks
  213. }
  214. $kw = (int)date('W', $t);
  215. if ($kw === 0) {
  216. $kw = 1 + (int)date('W', $t - DAY * (int)date('w', $t));
  217. $y--;
  218. }
  219. return str_pad((string)$kw, 2, '0', STR_PAD_LEFT) . '/' . $y;
  220. }
  221. /**
  222. * Get number of days since the start of the week.
  223. * 0=sunday to 7=saturday (default)
  224. *
  225. * @param int $num Number of day.
  226. * @return int Days since the start of the week.
  227. */
  228. public static function cWeekMod($num) {
  229. $base = 6;
  230. return (int)($num - $base * floor($num / $base));
  231. }
  232. /**
  233. * Calculate the beginning of a calender week
  234. * if no calendar week is given get the beginning of the first week of the year
  235. *
  236. * @param int $year (format xxxx)
  237. * @param int $cWeek (optional, defaults to first, range 1...52/53)
  238. * @return int Timestamp
  239. */
  240. public static function cWeekBeginning($year, $cWeek = 0) {
  241. if ($cWeek <= 1 || $cWeek > static::cWeeks($year)) {
  242. $first = mktime(0, 0, 0, 1, 1, $year);
  243. $weekDay = (int)date('w', $first);
  244. if ($weekDay <= 4) {
  245. /* Thursday or less: back to Monday */
  246. $firstmonday = mktime(0, 0, 0, 1, 1 - ($weekDay - 1), $year);
  247. } elseif ($weekDay !== 1) {
  248. /* Back to Monday */
  249. $firstmonday = mktime(0, 0, 0, 1, 1 + (7 - $weekDay + 1), $year);
  250. } else {
  251. $firstmonday = $first;
  252. }
  253. return $firstmonday;
  254. }
  255. $monday = strtotime($year . 'W' . static::pad((string)$cWeek) . '1');
  256. return $monday;
  257. }
  258. /**
  259. * Calculate the ending of a calenderweek
  260. * if no cweek is given get the ending of the last week of the year
  261. *
  262. * @param int $year (format xxxx)
  263. * @param int $cWeek (optional, defaults to last, range 1...52/53)
  264. * @return int Timestamp
  265. */
  266. public static function cWeekEnding($year, $cWeek = 0) {
  267. if ($cWeek < 1 || $cWeek >= static::cWeeks($year)) {
  268. return static::cWeekBeginning($year + 1) - 1;
  269. }
  270. return static::cWeekBeginning($year, $cWeek + 1) - 1;
  271. }
  272. /**
  273. * Calculate the amount of calender weeks in a year
  274. *
  275. * @param int|null $year (format xxxx, defaults to current year)
  276. * @return int Amount of weeks - 52 or 53
  277. */
  278. public static function cWeeks($year = null) {
  279. if ($year === null) {
  280. $year = date('Y');
  281. }
  282. return (int)date('W', mktime(23, 59, 59, 12, 28, $year));
  283. }
  284. /**
  285. * Handles month/year increment calculations in a safe way, avoiding the pitfall of "fuzzy" month units.
  286. *
  287. * @param mixed $startDate Either a date string or a DateTime object
  288. * @param int $years Years to increment/decrement
  289. * @param int $months Months to increment/decrement
  290. * @param int $days Days
  291. * @param \DateTimeZone|string|int|null $timezone Timezone string or DateTimeZone object
  292. * @return object DateTime with incremented/decremented month/year values.
  293. */
  294. public function incrementDate($startDate, $years = 0, $months = 0, $days = 0, $timezone = null) {
  295. $dateTime = $startDate;
  296. if (!is_object($startDate)) {
  297. $dateTime = new CakeFrozenTime($startDate);
  298. if ($timezone) {
  299. $dateTime = $dateTime->setTimezone($this->safeCreateDateTimeZone($timezone));
  300. }
  301. }
  302. $startingTimeStamp = $dateTime->getTimestamp();
  303. // Get the month value of the given date:
  304. $monthString = date('Y-m', $startingTimeStamp);
  305. // Create a date string corresponding to the 1st of the give month,
  306. // making it safe for monthly/yearly calculations:
  307. $safeDateString = "first day of $monthString";
  308. // offset is wrong
  309. $months++;
  310. // Increment date by given month/year increments:
  311. $incrementedDateString = "$safeDateString $months month $years year";
  312. $newTimeStamp = strtotime($incrementedDateString) + $days * DAY;
  313. $newDate = DateTime::createFromFormat('U', (string)$newTimeStamp);
  314. return $newDate;
  315. }
  316. /**
  317. * Get the age bounds (min, max) as timestamp that would result in the given age(s)
  318. * note: expects valid age (> 0 and < 120)
  319. *
  320. * @param int $firstAge
  321. * @param int|null $secondAge (defaults to first one if not specified)
  322. * @param bool $returnAsString
  323. * @param string|null $relativeTime
  324. * @return array Array('min'=>$min, 'max'=>$max);
  325. */
  326. public static function ageBounds($firstAge, $secondAge = null, $returnAsString = false, $relativeTime = null) {
  327. if ($secondAge === null) {
  328. $secondAge = $firstAge;
  329. }
  330. //TODO: other relative time then today should work as well
  331. $date = new CakeFrozenTime($relativeTime ?? 'now');
  332. $max = mktime(23, 23, 59, (int)$date->format('m'), (int)$date->format('d'), (int)$date->format('Y') - $firstAge);
  333. $min = mktime(0, 0, 1, (int)$date->format('m'), (int)$date->format('d') + 1, (int)$date->format('Y') - $secondAge - 1);
  334. if ($returnAsString) {
  335. $max = date(FORMAT_DB_DATE, $max);
  336. $min = date(FORMAT_DB_DATE, $min);
  337. }
  338. return ['min' => $min, 'max' => $max];
  339. }
  340. /**
  341. * For birthdays etc
  342. *
  343. * @param string $dateString
  344. * @param int $seconds
  345. * @return bool Success
  346. */
  347. public static function isInRange($dateString, $seconds) {
  348. $newDate = time();
  349. return static::difference($dateString, $newDate) <= $seconds;
  350. }
  351. /**
  352. * Outputs Date(time) Sting nicely formatted (+ localized!)
  353. *
  354. * Options:
  355. * - timezone: User's timezone
  356. * - default: Default string (defaults to "-----")
  357. * - oclock: Set to true to append oclock string
  358. *
  359. * @param string|null $dateString
  360. * @param string|null $format Format (YYYY-MM-DD, DD.MM.YYYY)
  361. * @param array<string, mixed> $options
  362. * @return string
  363. */
  364. public static function localDate(?string $dateString, ?string $format = null, array $options = []) {
  365. $defaults = [
  366. 'default' => '-----',
  367. 'timezone' => null,
  368. 'language' => 'en',
  369. 'oclock' => null,
  370. ];
  371. $options += $defaults;
  372. if ($options['timezone'] === null && strlen($dateString) === 10) {
  373. $options['timezone'] = static::_getDefaultOutputTimezone();
  374. }
  375. if ($dateString === null) {
  376. $dateString = time();
  377. }
  378. if ($options['timezone']) {
  379. $options['timezone'] = static::safeCreateDateTimeZone($options['timezone']);
  380. }
  381. $date = new CakeFrozenTime($dateString, $options['timezone']);
  382. if ($format === null) {
  383. if (is_int($dateString) || strpos($dateString, ' ') !== false) {
  384. $format = 'd.m.Y, H:i';
  385. } else {
  386. $format = 'd.m.Y';
  387. }
  388. }
  389. $date = static::formatLocalized($date, $format, $options['language']);
  390. if ($options['oclock']) {
  391. if (strpos($format, 'H:i') !== false) {
  392. $date .= ' ' . __d('tools', 'o\'clock');
  393. }
  394. }
  395. return $date;
  396. }
  397. /**
  398. * @param \DateTimeInterface $dt
  399. * @param string $format
  400. * @param string $language
  401. *
  402. * @return string
  403. */
  404. public static function formatLocalized(DateTimeInterface $dt, string $format, string $language = 'en'): string {
  405. $curTz = $dt->getTimezone();
  406. if ($curTz->getName() === 'Z') {
  407. // INTL don't know Z
  408. $curTz = new DateTimeZone('UTC');
  409. }
  410. $formatPattern = strtr($format, [
  411. 'D' => '{#1}',
  412. 'l' => '{#2}',
  413. 'M' => '{#3}',
  414. 'F' => '{#4}',
  415. ]);
  416. $strDate = $dt->format($formatPattern);
  417. $regEx = '~\{#\d\}~';
  418. while (preg_match($regEx, $strDate, $match)) {
  419. $IntlFormat = strtr($match[0], [
  420. '{#1}' => 'E',
  421. '{#2}' => 'EEEE',
  422. '{#3}' => 'MMM',
  423. '{#4}' => 'MMMM',
  424. ]);
  425. $fmt = datefmt_create(
  426. $language,
  427. IntlDateFormatter::FULL,
  428. IntlDateFormatter::FULL,
  429. $curTz,
  430. IntlDateFormatter::GREGORIAN,
  431. $IntlFormat,
  432. );
  433. $replace = $fmt ? datefmt_format($fmt, $dt) : '???';
  434. $strDate = str_replace($match[0], $replace, $strDate);
  435. }
  436. return $strDate;
  437. }
  438. /**
  439. * Multibyte wrapper for strftime.
  440. *
  441. * Handles utf8_encoding the result of strftime when necessary.
  442. *
  443. * @deprecated strftime() should be replaced in PHP 8.1+
  444. *
  445. * @param string $format Format string.
  446. * @param int $date Timestamp to format.
  447. * @return string formatted string with correct encoding.
  448. */
  449. protected static function _strftime($format, $date) {
  450. $format = strftime($format, $date);
  451. $encoding = Configure::read('App.encoding');
  452. if (!empty($encoding) && $encoding === 'UTF-8') {
  453. $valid = mb_check_encoding($format, $encoding);
  454. if (!$valid) {
  455. $format = utf8_encode($format);
  456. }
  457. }
  458. return $format;
  459. }
  460. /**
  461. * Outputs Date(time) Sting nicely formatted
  462. *
  463. * Options:
  464. * - timezone: User's timezone
  465. * - default: Default string (defaults to "-----")
  466. * - oclock: Set to true to append oclock string
  467. *
  468. * @param \Cake\I18n\I18nDateTimeInterface|string|null $dateString
  469. * @param string|null $format Format (YYYY-MM-DD, DD.MM.YYYY)
  470. * @param array<string, mixed> $options Options
  471. * @return string
  472. */
  473. public static function niceDate($dateString, $format = null, array $options = []) {
  474. $defaults = ['default' => '-----', 'timezone' => null];
  475. $options += $defaults;
  476. if ($options['timezone'] === null) {
  477. $options['timezone'] = static::_getDefaultOutputTimezone();
  478. }
  479. if ($options['timezone']) {
  480. $options['timezone'] = static::safeCreateDateTimeZone($options['timezone']);
  481. }
  482. if ($dateString === null) {
  483. return $options['default'];
  484. }
  485. if (!is_object($dateString)) {
  486. if (strlen($dateString) === 10) {
  487. $date = new FrozenDate($dateString);
  488. } else {
  489. $date = new CakeFrozenTime($dateString);
  490. }
  491. } else {
  492. $date = $dateString;
  493. }
  494. if ($format === null) {
  495. if ($date instanceof MutableDate || $date instanceof Date) {
  496. $format = FORMAT_NICE_YMD;
  497. } else {
  498. $format = FORMAT_NICE_YMDHM;
  499. }
  500. }
  501. $date = $date->setTimezone($options['timezone']);
  502. $ret = $date->format($format);
  503. if (!empty($options['oclock'])) {
  504. switch ($format) {
  505. case FORMAT_NICE_YMDHM:
  506. case FORMAT_NICE_YMDHMS:
  507. case FORMAT_NICE_HM:
  508. case FORMAT_NICE_HMS:
  509. $ret .= ' ' . __d('tools', 'o\'clock');
  510. break;
  511. }
  512. }
  513. return $ret;
  514. }
  515. /**
  516. * Takes time as hh:mm:ss or YYYY-MM-DD hh:mm:ss
  517. *
  518. * @param string $time
  519. * @return string Time in format hh:mm
  520. */
  521. public static function niceTime($time) {
  522. $pos = strpos($time, ' ');
  523. if ($pos !== false) {
  524. $time = substr($time, $pos + 1);
  525. }
  526. return substr($time, 0, 5);
  527. }
  528. /**
  529. * @return string
  530. */
  531. protected static function _getDefaultOutputTimezone() {
  532. return Configure::read('App.defaultOutputTimezone') ?: date_default_timezone_get();
  533. }
  534. /**
  535. * Return the translation to a specific week day
  536. *
  537. * @param int $day
  538. * 0=sunday to 7=saturday (default numbers)
  539. * @param bool $abbr (if abbreviation should be returned)
  540. * @param int $offset int 0-6 (defaults to 0) [1 => 1=monday to 7=sunday]
  541. * @return string translatedText
  542. */
  543. public static function dayName($day, $abbr = false, $offset = 0) {
  544. $days = [
  545. 'long' => [
  546. 'Sunday',
  547. 'Monday',
  548. 'Tuesday',
  549. 'Wednesday',
  550. 'Thursday',
  551. 'Friday',
  552. 'Saturday',
  553. ],
  554. 'short' => [
  555. 'Sun',
  556. 'Mon',
  557. 'Tue',
  558. 'Wed',
  559. 'Thu',
  560. 'Fri',
  561. 'Sat',
  562. ],
  563. ];
  564. $day = (int)$day;
  565. if ($offset) {
  566. $day = ($day + $offset) % 7;
  567. }
  568. if ($abbr) {
  569. return __d('tools', $days['short'][$day]);
  570. }
  571. return __d('tools', $days['long'][$day]);
  572. }
  573. /**
  574. * Return the translation to a specific week day
  575. *
  576. * @param int $month
  577. * 1..12
  578. * @param bool $abbr (if abbreviation should be returned)
  579. * @param array<string, mixed> $options
  580. * - appendDot (only for 3 letter abbr; defaults to false)
  581. * @return string translatedText
  582. */
  583. public static function monthName($month, $abbr = false, array $options = []) {
  584. $months = [
  585. 'long' => [
  586. 'January',
  587. 'February',
  588. 'March',
  589. 'April',
  590. 'May',
  591. 'June',
  592. 'July',
  593. 'August',
  594. 'September',
  595. 'October',
  596. 'November',
  597. 'December',
  598. ],
  599. 'short' => [
  600. 'Jan',
  601. 'Feb',
  602. 'Mar',
  603. 'Apr',
  604. 'May',
  605. 'Jun',
  606. 'Jul',
  607. 'Aug',
  608. 'Sep',
  609. 'Oct',
  610. 'Nov',
  611. 'Dec',
  612. ],
  613. ];
  614. $month = (int)($month - 1);
  615. if (!$abbr) {
  616. return __d('tools', $months['long'][$month]);
  617. }
  618. $monthName = __d('tools', $months['short'][$month]);
  619. if (!empty($options['appendDot']) && strlen(__d('tools', $months['long'][$month])) > 3) {
  620. $monthName .= '.';
  621. }
  622. return $monthName;
  623. }
  624. /**
  625. * Months
  626. *
  627. * Options:
  628. * - abbr
  629. *
  630. * @param array<int> $monthKeys
  631. * @param array<string, mixed> $options
  632. * @return array<string>
  633. */
  634. public static function monthNames(array $monthKeys = [], array $options = []) {
  635. if (!$monthKeys) {
  636. $monthKeys = range(1, 12);
  637. }
  638. $res = [];
  639. $abbr = $options['abbr'] ?? false;
  640. foreach ($monthKeys as $key) {
  641. $res[static::pad((string)$key)] = static::monthName($key, $abbr, $options);
  642. }
  643. return $res;
  644. }
  645. /**
  646. * Weekdays
  647. *
  648. * @param array<int> $dayKeys
  649. * @param array<string, mixed> $options
  650. * @return array<string>
  651. */
  652. public static function dayNames(array $dayKeys = [], array $options = []) {
  653. if (!$dayKeys) {
  654. $dayKeys = range(0, 6);
  655. }
  656. $res = [];
  657. $abbr = $options['abbr'] ?? false;
  658. $offset = $options['offset'] ?? 0;
  659. foreach ($dayKeys as $key) {
  660. $res[$key] = static::dayName($key, $abbr, $offset);
  661. }
  662. return $res;
  663. }
  664. /**
  665. * Returns the difference between a time and now in a "fuzzy" way.
  666. * Note that unlike [span], the "local" timestamp will always be the
  667. * current time. Displaying a fuzzy time instead of a date is usually
  668. * faster to read and understand.
  669. *
  670. * $span = fuzzy(time() - 10); // "moments ago"
  671. * $span = fuzzy(time() + 20); // "in moments"
  672. *
  673. * @param int $timestamp "remote" timestamp
  674. * @return string
  675. */
  676. public static function fuzzy($timestamp) {
  677. // Determine the difference in seconds
  678. $offset = abs(time() - $timestamp);
  679. return static::fuzzyFromOffset($offset, $timestamp <= time());
  680. }
  681. /**
  682. * @param int $offset in seconds
  683. * @param string|bool|null $past (defaults to null: return plain text)
  684. * - new: if not boolean but a string use this as translating text
  685. * @return string text (i18n!)
  686. */
  687. public static function fuzzyFromOffset($offset, $past = null) {
  688. if ($offset <= MINUTE) {
  689. $span = 'moments';
  690. } elseif ($offset < (MINUTE * 20)) {
  691. $span = 'a few minutes';
  692. } elseif ($offset < HOUR) {
  693. $span = 'less than an hour';
  694. } elseif ($offset < (HOUR * 4)) {
  695. $span = 'a couple of hours';
  696. } elseif ($offset < DAY) {
  697. $span = 'less than a day';
  698. } elseif ($offset < (DAY * 2)) {
  699. $span = 'about a day';
  700. } elseif ($offset < (DAY * 4)) {
  701. $span = 'a couple of days';
  702. } elseif ($offset < WEEK) {
  703. $span = 'less than a week';
  704. } elseif ($offset < (WEEK * 2)) {
  705. $span = 'about a week';
  706. } elseif ($offset < MONTH) {
  707. $span = 'less than a month';
  708. } elseif ($offset < (MONTH * 2)) {
  709. $span = 'about a month';
  710. } elseif ($offset < (MONTH * 4)) {
  711. $span = 'a couple of months';
  712. } elseif ($offset < YEAR) {
  713. $span = 'less than a year';
  714. } elseif ($offset < (YEAR * 2)) {
  715. $span = 'about a year';
  716. } elseif ($offset < (YEAR * 4)) {
  717. $span = 'a couple of years';
  718. } elseif ($offset < (YEAR * 8)) {
  719. $span = 'a few years';
  720. } elseif ($offset < (YEAR * 12)) {
  721. $span = 'about a decade';
  722. } elseif ($offset < (YEAR * 24)) {
  723. $span = 'a couple of decades';
  724. } elseif ($offset < (YEAR * 64)) {
  725. $span = 'several decades';
  726. } else {
  727. $span = 'a long time';
  728. }
  729. if ($past === true) {
  730. // This is in the past
  731. return __d('tools', '{0} ago', __d('tools', $span));
  732. }
  733. if ($past === false) {
  734. // This in the future
  735. return __d('tools', 'in {0}', __d('tools', $span));
  736. }
  737. if ($past !== null) {
  738. // Custom translation
  739. return __d('tools', $past, __d('tools', $span));
  740. }
  741. return __d('tools', $span);
  742. }
  743. /**
  744. * Time length to human readable format.
  745. *
  746. * @see timeAgoInWords()
  747. * @param int $seconds
  748. * @param string|null $format
  749. * @param array<string, mixed> $options
  750. * - boolean v: verbose
  751. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  752. * - int: accuracy (how many sub-formats displayed?) //TODO
  753. * @return string
  754. */
  755. public static function lengthOfTime($seconds, $format = null, array $options = []) {
  756. $defaults = ['verbose' => true, 'zero' => false, 'separator' => ', ', 'default' => ''];
  757. $options += $defaults;
  758. if (!$options['verbose']) {
  759. $s = [
  760. 'm' => 'mth',
  761. 'd' => 'd',
  762. 'h' => 'h',
  763. 'i' => 'm',
  764. 's' => 's',
  765. ];
  766. $p = $s;
  767. } else {
  768. $s = [
  769. 'm' => ' ' . __d('tools', 'Month'), # translated
  770. 'd' => ' ' . __d('tools', 'Day'),
  771. 'h' => ' ' . __d('tools', 'Hour'),
  772. 'i' => ' ' . __d('tools', 'Minute'),
  773. 's' => ' ' . __d('tools', 'Second'),
  774. ];
  775. $p = [
  776. 'm' => ' ' . __d('tools', 'Months'), # translated
  777. 'd' => ' ' . __d('tools', 'Days'),
  778. 'h' => ' ' . __d('tools', 'Hours'),
  779. 'i' => ' ' . __d('tools', 'Minutes'),
  780. 's' => ' ' . __d('tools', 'Seconds'),
  781. ];
  782. }
  783. if (!isset($format)) {
  784. if (floor($seconds / DAY) > 0) {
  785. $format = 'Dh';
  786. } elseif (floor($seconds / 3600) > 0) {
  787. $format = 'Hi';
  788. } elseif (floor($seconds / 60) > 0) {
  789. $format = 'Is';
  790. } else {
  791. $format = 'S';
  792. }
  793. }
  794. $ret = '';
  795. $j = 0;
  796. $length = mb_strlen($format);
  797. for ($i = 0; $i < $length; $i++) {
  798. switch (mb_substr($format, $i, 1)) {
  799. case 'D':
  800. $str = floor($seconds / 86400);
  801. break;
  802. case 'd':
  803. $str = floor((int)($seconds / 86400) % 30);
  804. break;
  805. case 'H':
  806. $str = floor($seconds / 3600);
  807. break;
  808. case 'h':
  809. $str = floor((int)($seconds / 3600) % 24);
  810. break;
  811. case 'I':
  812. $str = floor($seconds / 60);
  813. break;
  814. case 'i':
  815. $str = floor((int)($seconds / 60) % 60);
  816. break;
  817. case 'S':
  818. $str = $seconds;
  819. break;
  820. case 's':
  821. $str = floor($seconds % 60);
  822. break;
  823. default:
  824. return '';
  825. }
  826. if ($str > 0 || $j > 0 || $options['zero'] || $i === mb_strlen($format) - 1) {
  827. if ($j > 0) {
  828. $ret .= $options['separator'];
  829. }
  830. $j++;
  831. $x = mb_strtolower(mb_substr($format, $i, 1));
  832. if ($str === 1) {
  833. $ret .= $str . $s[$x];
  834. } else {
  835. $title = $p[$x];
  836. if (!empty($options['plural'])) {
  837. if (mb_substr($title, -1, 1) === 'e') {
  838. $title .= $options['plural'];
  839. }
  840. }
  841. $ret .= $str . $title;
  842. }
  843. }
  844. }
  845. return $ret;
  846. }
  847. /**
  848. * Time relative to NOW in human readable format - absolute (negative as well as positive)
  849. * //TODO: make "now" adjustable
  850. *
  851. * @param mixed $date
  852. * @param string|null $format Format
  853. * @param array<string, mixed> $options Options
  854. * - default, separator
  855. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  856. * - verbose/past/future: string with %s or boolean true/false
  857. * @return array|string
  858. */
  859. public static function relLengthOfTime($date, $format = null, array $options = []) {
  860. $dateTime = $date;
  861. if ($date !== null && !is_object($date)) {
  862. $dateTime = static::parse($date);
  863. }
  864. if ($dateTime !== null) {
  865. $date = $dateTime->format('U');
  866. $sec = time() - $date;
  867. $type = ($sec > 0) ? -1 : (($sec < 0) ? 1 : 0);
  868. $sec = abs($sec);
  869. } else {
  870. $sec = 0;
  871. $type = 0;
  872. }
  873. $defaults = [
  874. 'verbose' => __d('tools', 'justNow'), 'zero' => false, 'separator' => ', ',
  875. 'future' => __d('tools', 'In %s'), 'past' => __d('tools', '%s ago'), 'default' => ''];
  876. $options += $defaults;
  877. $ret = static::lengthOfTime($sec, $format, $options);
  878. if ($type == 1) {
  879. if ($options['future'] !== false) {
  880. return sprintf($options['future'], $ret);
  881. }
  882. return ['future' => $ret];
  883. }
  884. if ($type == -1) {
  885. if ($options['past'] !== false) {
  886. return sprintf($options['past'], $ret);
  887. }
  888. return ['past' => $ret];
  889. }
  890. if ($options['verbose'] !== false) {
  891. return $options['verbose'];
  892. }
  893. return $options['default'];
  894. }
  895. /**
  896. * Returns true if given datetime string was day before yesterday.
  897. *
  898. * @param \Cake\Chronos\ChronosInterface $date Datetime
  899. * @return bool True if datetime string was day before yesterday
  900. */
  901. public static function wasDayBeforeYesterday($date) {
  902. return $date->toDateString() === static::now()->subDays(2)->toDateString();
  903. }
  904. /**
  905. * Returns true if given datetime string is the day after tomorrow.
  906. *
  907. * @param \Cake\Chronos\ChronosInterface $date Datetime
  908. * @return bool True if datetime string is day after tomorrow
  909. */
  910. public static function isDayAfterTomorrow($date) {
  911. return $date->toDateString() === static::now()->addDays(2)->toDateString();
  912. }
  913. /**
  914. * Returns true if given datetime string is not today AND is in the future.
  915. *
  916. * @param string $dateString Datetime string or Unix timestamp
  917. * @param \DateTimeZone|string|null $timezone User's timezone
  918. * @return bool True if datetime is not today AND is in the future
  919. */
  920. public static function isNotTodayAndInTheFuture($dateString, $timezone = null) {
  921. $date = new CakeFrozenTime($dateString, $timezone);
  922. $date = $date->format('U');
  923. return date(FORMAT_DB_DATE, (int)$date) > date(FORMAT_DB_DATE, time());
  924. }
  925. /**
  926. * Returns true if given datetime string is not now AND is in the future.
  927. *
  928. * @param \DateTimeInterface|string $date Datetime string or Unix timestamp
  929. * @param \DateTimeZone|string|null $timezone User's timezone
  930. * @return bool True if datetime is not today AND is in the future
  931. */
  932. public static function isInTheFuture($date, $timezone = null) {
  933. if (!($date instanceof DateTimeInterface)) {
  934. $date = new CakeFrozenTime($date, $timezone);
  935. }
  936. $date = $date->format('U');
  937. return date(FORMAT_DB_DATETIME, (int)$date) > date(FORMAT_DB_DATETIME, time());
  938. }
  939. /**
  940. * Try to parse date from various input formats
  941. * - DD.MM.YYYY, DD/MM/YYYY, YYYY-MM-DD, YYYY, YYYY-MM, ...
  942. * - i18n: Today, Yesterday, Tomorrow
  943. *
  944. * @param string $date to parse
  945. * @param string|null $format Format to parse (null = auto)
  946. * @param string $type
  947. * - start: first second of this interval
  948. * - end: last second of this interval
  949. * @return string timestamp
  950. */
  951. public static function parseLocalizedDate($date, $format = null, $type = 'start') {
  952. $date = trim($date);
  953. $i18n = [
  954. strtolower(__d('tools', 'Today')) => ['start' => date(FORMAT_DB_DATETIME, mktime(0, 0, 0, (int)date('m'), (int)date('d'), (int)date('Y'))), 'end' => date(FORMAT_DB_DATETIME, mktime(23, 59, 59, (int)date('m'), (int)date('d'), (int)date('Y')))],
  955. strtolower(__d('tools', 'Tomorrow')) => ['start' => date(FORMAT_DB_DATETIME, mktime(0, 0, 0, (int)date('m'), (int)date('d'), (int)date('Y')) + DAY), 'end' => date(FORMAT_DB_DATETIME, mktime(23, 59, 59, (int)date('m'), (int)date('d'), (int)date('Y')) + DAY)],
  956. strtolower(__d('tools', 'Yesterday')) => ['start' => date(FORMAT_DB_DATETIME, mktime(0, 0, 0, (int)date('m'), (int)date('d'), (int)date('Y')) - DAY), 'end' => date(FORMAT_DB_DATETIME, mktime(23, 59, 59, (int)date('m'), (int)date('d'), (int)date('Y')) - DAY)],
  957. strtolower(__d('tools', 'The day after tomorrow')) => ['start' => date(FORMAT_DB_DATETIME, mktime(0, 0, 0, (int)date('m'), (int)date('d'), (int)date('Y')) + 2 * DAY), 'end' => date(FORMAT_DB_DATETIME, mktime(23, 59, 59, (int)date('m'), (int)date('d'), (int)date('Y')) + 2 * DAY)],
  958. strtolower(__d('tools', 'The day before yesterday')) => ['start' => date(FORMAT_DB_DATETIME, mktime(0, 0, 0, (int)date('m'), (int)date('d'), (int)date('Y')) - 2 * DAY), 'end' => date(FORMAT_DB_DATETIME, mktime(23, 59, 59, (int)date('m'), (int)date('d'), (int)date('Y')) - 2 * DAY)],
  959. ];
  960. if (isset($i18n[strtolower($date)])) {
  961. return $i18n[strtolower($date)][$type];
  962. }
  963. if ($format) {
  964. $res = DateTime::createFromFormat($format, $date);
  965. $res = $res->format(FORMAT_DB_DATE) . ' ' . ($type === 'end' ? '23:59:59' : '00:00:00');
  966. return $res;
  967. }
  968. if (strpos($date, '.') !== false) {
  969. $explode = explode('.', $date, 3);
  970. $explode = array_reverse($explode);
  971. } elseif (strpos($date, '/') !== false) {
  972. $explode = explode('/', $date, 3);
  973. $explode = array_reverse($explode);
  974. } elseif (strpos($date, '-') !== false) {
  975. $explode = explode('-', $date, 3);
  976. } else {
  977. $explode = [$date];
  978. }
  979. $count = count($explode);
  980. for ($i = 0; $i < $count; $i++) {
  981. $explode[$i] = static::pad($explode[$i]);
  982. }
  983. $explode[0] = static::pad($explode[0], 4, '20');
  984. if (count($explode) === 3) {
  985. return implode('-', $explode) . ' ' . ($type === 'end' ? '23:59:59' : '00:00:00');
  986. }
  987. if (count($explode) === 2) {
  988. return implode('-', $explode) . '-' . ($type === 'end' ? static::daysInMonth((int)$explode[0], (int)$explode[1]) : '01') . ' ' . ($type === 'end' ? '23:59:59' : '00:00:00');
  989. }
  990. return $explode[0] . '-' . ($type === 'end' ? '12' : '01') . '-' . ($type === 'end' ? '31' : '01') . ' ' . ($type === 'end' ? '23:59:59' : '00:00:00');
  991. }
  992. /**
  993. * Parse a period (from ... to)
  994. *
  995. * @param string $searchString Search string to parse
  996. * @param array<string, mixed> $options
  997. * - separator (defaults to space [ ])
  998. * - format (defaults to Y-m-d H:i:s)
  999. * @return array period [0=>min, 1=>max]
  1000. */
  1001. public static function period($searchString, array $options = []) {
  1002. if (strpos($searchString, ' ') !== false) {
  1003. $filters = explode(' ', $searchString);
  1004. $filters = [array_shift($filters), array_pop($filters)];
  1005. } else {
  1006. $filters = [$searchString, $searchString];
  1007. }
  1008. $min = $filters[0];
  1009. $max = $filters[1];
  1010. $min = static::parseLocalizedDate($min);
  1011. $max = static::parseLocalizedDate($max, null, 'end');
  1012. return [$min, $max];
  1013. }
  1014. /**
  1015. * Return SQL snippet for a period (beginning till end).
  1016. *
  1017. * @param string $searchString to parse
  1018. * @param string $fieldName (Model.field)
  1019. * @param array<string, mixed> $options (see Time::period)
  1020. * @return string query SQL Query
  1021. */
  1022. public static function periodAsSql($searchString, $fieldName, array $options = []) {
  1023. $period = static::period($searchString, $options);
  1024. return static::daysAsSql($period[0], $period[1], $fieldName);
  1025. }
  1026. /**
  1027. * Returns a partial SQL string to search for all records between two dates.
  1028. *
  1029. * @param \DateTimeInterface|string|int $begin UNIX timestamp, strtotime() valid string or DateTime object
  1030. * @param \DateTimeInterface|string|int $end UNIX timestamp, strtotime() valid string or DateTime object
  1031. * @param string $fieldName Name of database field to compare with
  1032. * @param \DateTimeZone|string|null $timezone Timezone string or DateTimeZone object
  1033. * @return string Partial SQL string.
  1034. */
  1035. public static function daysAsSql($begin, $end, $fieldName, $timezone = null) {
  1036. $begin = new CakeFrozenTime($begin, $timezone);
  1037. $begin = $begin->format('U');
  1038. $end = new CakeFrozenTime($end, $timezone);
  1039. $end = $end->format('U');
  1040. $begin = date('Y-m-d', (int)$begin) . ' 00:00:00';
  1041. $end = date('Y-m-d', (int)$end) . ' 23:59:59';
  1042. return "($fieldName >= '$begin') AND ($fieldName <= '$end')";
  1043. }
  1044. /**
  1045. * Returns a partial SQL string to search for all records between two times
  1046. * occurring on the same day.
  1047. *
  1048. * @param \DateTimeInterface|string|int $dateString UNIX timestamp, strtotime() valid string or DateTime object
  1049. * @param string $fieldName Name of database field to compare with
  1050. * @param \DateTimeZone|string|null $timezone Timezone string or DateTimeZone object
  1051. * @return string Partial SQL string.
  1052. */
  1053. public static function dayAsSql($dateString, $fieldName, $timezone = null) {
  1054. return static::daysAsSql($dateString, $dateString, $fieldName, $timezone);
  1055. }
  1056. /**
  1057. * Hours, minutes
  1058. * e.g. 9.3 => 9.5
  1059. *
  1060. * @param int $value
  1061. * @return float
  1062. */
  1063. public static function standardToDecimalTime($value) {
  1064. $base = (int)$value;
  1065. $tmp = $value - $base;
  1066. $tmp *= 100;
  1067. $tmp *= 1 / 60;
  1068. $value = $base + $tmp;
  1069. return $value;
  1070. }
  1071. /**
  1072. * Hours, minutes
  1073. * e.g. 9.5 => 9.3
  1074. * with pad=2: 9.30
  1075. *
  1076. * @param float|int $value
  1077. * @param int|null $pad
  1078. * @param string $decPoint
  1079. * @return string
  1080. */
  1081. public static function decimalToStandardTime($value, $pad = null, $decPoint = '.') {
  1082. $base = (int)$value;
  1083. $tmp = $value - $base;
  1084. $tmp /= 1 / 60;
  1085. $tmp /= 100;
  1086. $value = $base + $tmp;
  1087. if ($pad === null) {
  1088. return (string)$value;
  1089. }
  1090. return number_format($value, $pad, $decPoint, '');
  1091. }
  1092. /**
  1093. * Parse 2,5 - 2.5 2:30 2:31:58 or even 2011-11-12 10:10:10
  1094. * now supports negative values like -2,5 -2,5 -2:30 -:30 or -4
  1095. *
  1096. * @param string $duration
  1097. * @param array<string> $allowed
  1098. * @return int Seconds
  1099. */
  1100. public static function parseLocalTime($duration, array $allowed = [':', '.', ',']) {
  1101. if (!$duration) {
  1102. return 0;
  1103. }
  1104. $parts = explode(' ', $duration);
  1105. $duration = array_pop($parts);
  1106. if (strpos($duration, '.') !== false && in_array('.', $allowed, true)) {
  1107. $duration = static::decimalToStandardTime((float)$duration, 2, ':');
  1108. } elseif (strpos($duration, ',') !== false && in_array(',', $allowed, true)) {
  1109. $duration = str_replace(',', '.', $duration);
  1110. $duration = static::decimalToStandardTime((float)$duration, 2, ':');
  1111. }
  1112. // now there is only the time schema left...
  1113. $pieces = explode(':', $duration, 3);
  1114. $res = 0;
  1115. $hours = abs((int)$pieces[0]) * HOUR;
  1116. //echo pre($hours);
  1117. $isNegative = (strpos((string)$pieces[0], '-') !== false ? true : false);
  1118. if (count($pieces) === 3) {
  1119. $res += $hours + ((int)$pieces[1]) * MINUTE + ((int)$pieces[2]) * SECOND;
  1120. } elseif (count($pieces) === 2) {
  1121. $res += $hours + ((int)$pieces[1]) * MINUTE;
  1122. } else {
  1123. $res += $hours;
  1124. }
  1125. if ($isNegative) {
  1126. return -$res;
  1127. }
  1128. return $res;
  1129. }
  1130. /**
  1131. * Parse 2022-11-12 or 12.11.2022 or even 12.11.22
  1132. *
  1133. * @param string $date
  1134. * @param array<string> $allowed
  1135. * @return int Seconds
  1136. */
  1137. public static function parseLocalDate($date, array $allowed = ['.', '-']) {
  1138. $datePieces = explode(' ', $date, 2);
  1139. $date = array_shift($datePieces);
  1140. if (strpos($date, '.') !== false) {
  1141. $pieces = explode('.', $date);
  1142. $year = $pieces[2];
  1143. if (strlen($year) === 2) {
  1144. if ($year < 50) {
  1145. $year = '20' . $year;
  1146. } else {
  1147. $year = '19' . $year;
  1148. }
  1149. }
  1150. $date = mktime(0, 0, 0, (int)$pieces[1], (int)$pieces[0], (int)$year);
  1151. } elseif (strpos($date, '-') !== false) {
  1152. //$pieces = explode('-', $date);
  1153. $date = strtotime($date);
  1154. } else {
  1155. return 0;
  1156. }
  1157. return $date;
  1158. }
  1159. /**
  1160. * Returns nicely formatted duration difference
  1161. * as string like 2:30 (H:MM) or 2:30:06 (H:MM:SS) etc.
  1162. * Note that the more than days is currently not supported accurately.
  1163. *
  1164. * E.g. for days and hours set format to: $d:$H
  1165. *
  1166. * @param \DateInterval|int $duration Duration in seconds or as DateInterval object
  1167. * @param string $format Defaults to hours, minutes and seconds
  1168. * @return string Time
  1169. */
  1170. public static function duration($duration, $format = '%h:%I:%S') {
  1171. if (!$duration instanceof DateInterval) {
  1172. $d1 = new CakeFrozenTime();
  1173. $d2 = new CakeFrozenTime();
  1174. $d2 = $d2->add(new DateInterval('PT' . $duration . 'S'));
  1175. $duration = $d2->diff($d1);
  1176. }
  1177. if (stripos($format, 'd') === false && $duration->d) {
  1178. $duration->h += $duration->d * 24;
  1179. }
  1180. if (stripos($format, 'h') === false && $duration->h) {
  1181. $duration->i += $duration->h * 60;
  1182. }
  1183. if (stripos($format, 'i') === false && $duration->i) {
  1184. $duration->s += $duration->m * 60;
  1185. }
  1186. return $duration->format($format);
  1187. }
  1188. /**
  1189. * Returns nicely formatted duration difference
  1190. * as string like 2:30 or 2:30:06.
  1191. * Note that the more than hours is currently not supported.
  1192. *
  1193. * Note that duration with DateInterval supports only values < month with accuracy,
  1194. * as it approximates month as "30".
  1195. *
  1196. * @deprecated Use duration() instead?
  1197. * @param \DateInterval|int $duration Duration in seconds or as DateInterval object
  1198. * @param string $format Defaults to hours and minutes
  1199. * @return string Time
  1200. */
  1201. public static function buildTime($duration, $format = 'H:MM:SS') {
  1202. if ($duration instanceof DateInterval) {
  1203. $m = $duration->invert ? -1 : 1;
  1204. $duration = ($duration->y * YEAR) +
  1205. ($duration->m * MONTH) +
  1206. ($duration->d * DAY) +
  1207. ($duration->h * HOUR) +
  1208. ($duration->i * MINUTE) +
  1209. $duration->s;
  1210. $duration *= $m;
  1211. }
  1212. if ($duration < 0) {
  1213. $duration = abs($duration);
  1214. $isNegative = true;
  1215. }
  1216. $minutes = $duration % HOUR;
  1217. $hours = ($duration - $minutes) / HOUR;
  1218. $res = [];
  1219. if (strpos($format, 'H') !== false) {
  1220. $res[] = (int)$hours . ':' . static::pad((string)($minutes / MINUTE));
  1221. } else {
  1222. $res[] = (int)($minutes / MINUTE);
  1223. }
  1224. if (strpos($format, 'SS') !== false) {
  1225. $seconds = $duration % MINUTE;
  1226. $res[] = static::pad((string)$seconds);
  1227. }
  1228. $res = implode(':', $res);
  1229. if (!empty($isNegative)) {
  1230. $res = '-' . $res;
  1231. }
  1232. return $res;
  1233. }
  1234. /**
  1235. * Return strings like 2:33:99 from seconds etc
  1236. *
  1237. * @param int $duration Duration in seconds
  1238. * @return string Time
  1239. */
  1240. public static function buildDefaultTime($duration): string {
  1241. $minutes = $duration % HOUR;
  1242. $duration -= $minutes;
  1243. $hours = $duration / HOUR;
  1244. $seconds = $minutes % MINUTE;
  1245. return static::pad((string)$hours) . ':' . static::pad((string)($minutes / MINUTE)) . ':' . static::pad((string)($seconds / SECOND));
  1246. }
  1247. /**
  1248. * @param string $value
  1249. * @param int $length
  1250. * @param string $string
  1251. * @return string
  1252. */
  1253. public static function pad($value, $length = 2, $string = '0') {
  1254. return str_pad((string)(int)$value, $length, $string, STR_PAD_LEFT);
  1255. }
  1256. }