Time.php 40 KB

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