TimeLib.php 35 KB

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