FrozenTime.php 38 KB

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