TimeLib.php 34 KB

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