DateTime.php 39 KB

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