TimeLib.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  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 = null, $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. * Calculate the age using start and optional end date.
  82. * End date defaults to current date.
  83. *
  84. * @param start date (if empty, use today)
  85. * @param end date (if empty, use today)
  86. * start and end cannot be both empty!
  87. * @param accuracy (year only = 0, incl months/days = 2)
  88. * if > 0, returns array!!! ('days'=>x,'months'=>y,'years'=>z)
  89. *
  90. * does this work too?
  91. * $now = mktime(0,0,0,date("m"),date("d"),date("Y"));
  92. * $birth = mktime(0,0,0, $monat, $tag, $jahr);
  93. * $age = intval(($now - $birth) / (3600 * 24 * 365));
  94. * @return int age (0 if both timestamps are equal or empty, -1 on invalid dates)
  95. */
  96. public static function age($start = null, $end = null, $accuracy = 0) {
  97. if (empty($start) && empty($end) || $start == $end) {
  98. return 0;
  99. }
  100. if (is_int($start)) {
  101. $start = date(FORMAT_DB_DATE, $start);
  102. }
  103. if (is_int($end)) {
  104. $end = date(FORMAT_DB_DATE, $end);
  105. }
  106. $endDate = new DateTime($end);
  107. $startDate = new DateTime($start);
  108. if ($startDate > $endDate) {
  109. return -1;
  110. }
  111. $oDateInterval = $endDate->diff($startDate);
  112. return $oDateInterval->y;
  113. }
  114. /**
  115. * Try to return the age only with the year available
  116. * can be e.g. 22/23
  117. *
  118. * @param int $year
  119. * @param int $month (optional)
  120. * @return int Age
  121. */
  122. public static function ageByYear($year, $month = null) {
  123. if ($month === null) {
  124. $maxAge = self::age(mktime(0, 0, 0, 1, 1, $year));
  125. $minAge = self::age(mktime(23, 59, 59, 12, 31, $year));
  126. $ages = array_unique(array($minAge, $maxAge));
  127. return implode('/', $ages);
  128. }
  129. if (date('n') == $month) {
  130. $maxAge = self::age(mktime(0, 0, 0, $month, 1, $year));
  131. $minAge = self::age(mktime(23, 59, 59, $month, self::daysInMonth($year, $month), $year));
  132. $ages = array_unique(array($minAge, $maxAge));
  133. return implode('/', $ages);
  134. }
  135. return self::age(mktime(0, 0, 0, $month, 1, $year));
  136. }
  137. /**
  138. * @param int $year
  139. * @param int $sign
  140. * @return mixed
  141. */
  142. public static function ageByHoroscope($year, $sign) {
  143. App::uses('ZodiacLib', 'Tools.Misc');
  144. $Zodiac = new ZodiacLib();
  145. $range = $Zodiac->getRange($sign);
  146. if ($sign == ZodiacLib::SIGN_CAPRICORN) {
  147. // undefined
  148. return array(date('Y') - $year - 1, date('Y') - $year);
  149. }
  150. if ($range[0][0] > date('m') || ($range[0][0] == date('m') && $range[0][1] > date('d'))) {
  151. // not over
  152. return date('Y') - $year - 1;
  153. }
  154. if ($range[1][0] < date('m') || ($range[1][0] == date('m') && $range[1][1] <= date('d'))) {
  155. // over
  156. return date('Y') - $year;
  157. }
  158. return array(date('Y') - $year - 1, date('Y') - $year);
  159. }
  160. /**
  161. * Rounded age depended on steps (e.g. age 16 with steps = 10 => "11-20")
  162. * //FIXME
  163. * //TODO: move to helper?
  164. *
  165. * @param int $year
  166. * @param int $month
  167. * @param int $day
  168. * @param int $steps
  169. * @return mixed
  170. */
  171. public static function ageRange($year, $month = null, $day = null, $steps = 1) {
  172. if ($month == null && $day == null) {
  173. $age = date('Y') - $year - 1;
  174. } elseif ($day == null) {
  175. if ($month >= date('m'))
  176. $age = date('Y') - $year - 1;
  177. else
  178. $age = date('Y') - $year;
  179. } else {
  180. if ($month > date('m') || ($month == date('m') && $day > date('d')))
  181. $age = date('Y') - $year - 1;
  182. else
  183. $age = date('Y') - $year;
  184. }
  185. if ($age % $steps == 0) {
  186. $lowerRange = $age - $steps + 1;
  187. $upperRange = $age;
  188. } else {
  189. $lowerRange = $age - ($age % $steps) + 1;
  190. $upperRange = $age - ($age % $steps) + $steps;
  191. }
  192. if ($lowerRange == $upperRange) {
  193. return $upperRange;
  194. }
  195. return array($lowerRange, $upperRange);
  196. }
  197. /**
  198. * Return the days of a given month.
  199. *
  200. * @param int $year
  201. * @param int $month
  202. */
  203. public static function daysInMonth($year, $month) {
  204. return date("t", mktime(0, 0, 0, $month, 1, $year));
  205. }
  206. /**
  207. * Calendar Week (current week of the year).
  208. * //TODO: use timestamp - or make the function able to use timestamps at least (besides dateString)
  209. *
  210. * date('W', $time) returns ISO6801 week number.
  211. * Exception: Dates of the calender week of the previous year return 0. In this case the cweek of the
  212. * last week of the previous year should be used.
  213. *
  214. * @param date in DB format - if none is passed, current day is used
  215. * @param int $relative - weeks relative to the date (+1 next, -1 previous etc)
  216. * @return string
  217. */
  218. public static function cWeek($dateString = null, $relative = 0) {
  219. //$time = self::fromString($dateString);
  220. if (!empty($dateString)) {
  221. $date = explode(' ', $dateString);
  222. list ($y, $m, $d) = explode('-', $date[0]);
  223. $t = mktime(0, 0, 0, $m, $d, $y);
  224. } else {
  225. $d = date('d');
  226. $m = date('m');
  227. $y = date('Y');
  228. $t = time();
  229. }
  230. $relative = (int)$relative;
  231. if ($relative != 0) {
  232. $t += WEEK * $relative; // 1day * 7 * relativeWeeks
  233. }
  234. if (($kw = date('W', $t)) === 0) {
  235. $kw = 1 + date($t - DAY * date('w', $t), 'W');
  236. $y--;
  237. }
  238. //echo "Der $d.$m.$y liegt in der Kalenderwoche $kw/$y";
  239. return $kw . '/' . $y;
  240. }
  241. /**
  242. * Return the timestamp to a day in a specific cweek
  243. * 0=sunday to 7=saturday (default)
  244. *
  245. * @return timestamp of the weekDay
  246. * @FIXME: offset
  247. * not needed, use localDate!
  248. */
  249. public static function cWeekDay($cweek, $year, $day) {
  250. $cweekBeginning = self::cweekBeginning($year, $cweek);
  251. return $cweekBeginning + $day * DAY;
  252. }
  253. /**
  254. * Get number of days since the start of the week.
  255. * 0=sunday to 7=saturday (default)
  256. *
  257. * @param int $num Number of day.
  258. * @return int Days since the start of the week.
  259. */
  260. public static function cWeekMod($num) {
  261. $base = 6;
  262. return ($num - $base * floor($num / $base));
  263. }
  264. /**
  265. * Calculate the beginning of a calenderweek
  266. * if no cweek is given get the beginning of the first week of the year
  267. *
  268. * @param year (format xxxx)
  269. * @param cweek (optional, defaults to first, range 1...52/53)
  270. */
  271. public static function cWeekBeginning($year, $cweek = null) {
  272. if ((int)$cweek <= 1 || (int)$cweek > self::cweeks($year)) {
  273. $first = mktime(0, 0, 0, 1, 1, $year);
  274. $wtag = date('w', $first);
  275. if ($wtag <= 4) {
  276. /*Donnerstag oder kleiner: auf den Montag zurückrechnen.*/
  277. $firstmonday = mktime(0, 0, 0, 1, 1 - ($wtag - 1), $year);
  278. } elseif ($wtag != 1) {
  279. /*auf den Montag nach vorne rechnen.*/
  280. $firstmonday = mktime(0, 0, 0, 1, 1 + (7 - $wtag + 1), $year);
  281. } else {
  282. $firstmonday = $first;
  283. }
  284. return $firstmonday;
  285. }
  286. $monday = strtotime($year . 'W' . self::pad($cweek) . '1');
  287. return $monday;
  288. }
  289. /**
  290. * Calculate the ending of a calenderweek
  291. * if no cweek is given get the ending of the last week of the year
  292. *
  293. * @param year (format xxxx)
  294. * @param cweek (optional, defaults to last, range 1...52/53)
  295. */
  296. public static function cWeekEnding($year, $cweek = null) {
  297. if ((int)$cweek < 1 || (int)$cweek >= self::cweeks($year)) {
  298. return self::cweekBeginning($year + 1) - 1;
  299. }
  300. return self::cweekBeginning($year, intval($cweek) + 1) - 1;
  301. }
  302. /**
  303. * Calculate the amount of calender weeks in a year
  304. *
  305. * @param year (format xxxx, defaults to current year)
  306. * @return int: 52 or 53
  307. */
  308. public static function cWeeks($year = null) {
  309. if ($year === null) {
  310. $year = date('Y');
  311. }
  312. return date('W', mktime(23, 59, 59, 12, 28, $year));
  313. }
  314. /**
  315. * @param year (format xxxx, defaults to current year)
  316. * @return bool Success
  317. */
  318. public static function isLeapYear($year) {
  319. if ($year % 4 != 0) {
  320. return false;
  321. }
  322. if ($year % 400 == 0) {
  323. return true;
  324. }
  325. if ($year > 1582 && $year % 100 == 0) {
  326. // if gregorian calendar (>1582), century not-divisible by 400 is not leap
  327. return false;
  328. }
  329. return true;
  330. }
  331. /**
  332. * Handles month/year increment calculations in a safe way, avoiding the pitfall of "fuzzy" month units.
  333. *
  334. * @param mixed $startDate Either a date string or a DateTime object
  335. * @param int $years Years to increment/decrement
  336. * @param int $months Months to increment/decrement
  337. * @param string|DateTimeZone $timezone Timezone string or DateTimeZone object
  338. * @return object DateTime with incremented/decremented month/year values.
  339. */
  340. public static function incrementDate($startDate, $years = 0, $months = 0, $days = 0, $timezone = null) {
  341. if (!is_object($startDate)) {
  342. $startDate = new DateTime($startDate);
  343. $startDate->setTimezone($timezone ? new DateTimeZone($timezone) : self::timezone());
  344. }
  345. $startingTimeStamp = $startDate->getTimestamp();
  346. // Get the month value of the given date:
  347. $monthString = date('Y-m', $startingTimeStamp);
  348. // Create a date string corresponding to the 1st of the give month,
  349. // making it safe for monthly/yearly calculations:
  350. $safeDateString = "first day of $monthString";
  351. // offset is wrong
  352. $months++;
  353. // Increment date by given month/year increments:
  354. $incrementedDateString = "$safeDateString $months month $years year";
  355. $newTimeStamp = strtotime($incrementedDateString) + $days * DAY;
  356. $newDate = DateTime::createFromFormat('U', $newTimeStamp);
  357. return $newDate;
  358. }
  359. /**
  360. * Get the age bounds (min, max) as timestamp that would result in the given age(s)
  361. * note: expects valid age (> 0 and < 120)
  362. *
  363. * @param $firstAge
  364. * @param $secondAge (defaults to first one if not specified)
  365. * @return array('min'=>$min, 'max'=>$max);
  366. */
  367. public static function ageBounds($firstAge, $secondAge = null, $returnAsString = false, $relativeTime = null) {
  368. if ($secondAge === null) {
  369. $secondAge = $firstAge;
  370. }
  371. //TODO: other relative time then today should work as well
  372. $Date = new DateTime($relativeTime !== null ? $relativeTime : 'now');
  373. $max = mktime(23, 23, 59, $Date->format('m'), $Date->format('d'), $Date->format('Y') - $firstAge);
  374. $min = mktime(0, 0, 1, $Date->format('m'), $Date->format('d') + 1, $Date->format('Y') - $secondAge - 1);
  375. if ($returnAsString) {
  376. $max = date(FORMAT_DB_DATE, $max);
  377. $min = date(FORMAT_DB_DATE, $min);
  378. }
  379. return array('min' => $min, 'max' => $max);
  380. }
  381. /**
  382. * For birthdays etc
  383. *
  384. * @param date
  385. * @param string days with +-
  386. * @param options
  387. */
  388. public static function isInRange($dateString, $seconds, $options = array()) {
  389. //$newDate = is_int($dateString) ? $dateString : strtotime($dateString);
  390. //$newDate += $seconds;
  391. $newDate = time();
  392. return self::difference($dateString, $newDate) <= $seconds;
  393. }
  394. /**
  395. * Outputs Date(time) Sting nicely formatted (+ localized!)
  396. *
  397. * Options:
  398. * - timezone: User's timezone
  399. * - default: Default string (defaults to "-----")
  400. * - oclock: Set to true to append oclock string
  401. *
  402. * @param string $dateString,
  403. * @param string $format Format (YYYY-MM-DD, DD.MM.YYYY)
  404. * @param array $options @return string
  405. * @return string
  406. */
  407. public static function localDate($dateString = null, $format = null, $options = array()) {
  408. $defaults = array('default' => '-----', 'timezone' => null);
  409. $options = array_merge($defaults, $options);
  410. if ($options['timezone'] === null && strlen($dateString) === 10) {
  411. $options['timezone'] = date_default_timezone_get();
  412. }
  413. if ($dateString === null) {
  414. $dateString = time();
  415. }
  416. $date = self::fromString($dateString, $options['timezone']);
  417. if ($date === null || $date === false || $date <= 0) {
  418. return $options['default'];
  419. }
  420. if ($format === null) {
  421. if (is_int($dateString) || strpos($dateString, ' ') !== false) {
  422. $format = FORMAT_LOCAL_YMDHM;
  423. } else {
  424. $format = FORMAT_LOCAL_YMD;
  425. }
  426. }
  427. $date = parent::_strftime($format, $date);
  428. if (!empty($options['oclock'])) {
  429. switch ($format) {
  430. case FORMAT_LOCAL_YMDHM:
  431. case FORMAT_LOCAL_YMDHMS:
  432. case FORMAT_LOCAL_YMDHM:
  433. case FORMAT_LOCAL_HM:
  434. case FORMAT_LOCAL_HMS:
  435. $date .= ' ' . __('o\'clock');
  436. break;
  437. }
  438. }
  439. return $date;
  440. }
  441. /**
  442. * Outputs Date(time) Sting nicely formatted
  443. *
  444. * Options:
  445. * - timezone: User's timezone
  446. * - default: Default string (defaults to "-----")
  447. * - oclock: Set to true to append oclock string
  448. *
  449. * @param string $dateString,
  450. * @param string $format Format (YYYY-MM-DD, DD.MM.YYYY)
  451. * @param array $options Options
  452. * @return string
  453. */
  454. public static function niceDate($dateString = null, $format = null, $options = array()) {
  455. $defaults = array('default' => '-----', 'timezone' => null);
  456. $options = array_merge($defaults, $options);
  457. if ($options['timezone'] === null && strlen($dateString) === 10) {
  458. $options['timezone'] = date_default_timezone_get();
  459. }
  460. if ($dateString === null) {
  461. $dateString = time();
  462. }
  463. $date = self::fromString($dateString, $options['timezone']);
  464. if ($date === null || $date === false || $date <= 0) {
  465. return $options['default'];
  466. }
  467. if ($format === null) {
  468. if (is_int($dateString) || strpos($dateString, ' ') !== false) {
  469. $format = FORMAT_NICE_YMDHM;
  470. } else {
  471. $format = FORMAT_NICE_YMD;
  472. }
  473. }
  474. $ret = date($format, $date);
  475. if (!empty($options['oclock'])) {
  476. switch ($format) {
  477. case FORMAT_NICE_YMDHM:
  478. case FORMAT_NICE_YMDHMS:
  479. case FORMAT_NICE_YMDHM:
  480. case FORMAT_NICE_HM:
  481. case FORMAT_NICE_HMS:
  482. $ret .= ' ' . __('o\'clock');
  483. break;
  484. }
  485. }
  486. return $ret;
  487. }
  488. /**
  489. * Takes time as hh:mm:ss or YYYY-MM-DD hh:mm:ss
  490. *
  491. * @param string $time
  492. * @return string Time in format hh:mm
  493. */
  494. public static function niceTime($time) {
  495. if (($pos = strpos($time, ' ')) !== false) {
  496. $time = substr($time, $pos + 1);
  497. }
  498. return substr($time, 0, 5);
  499. }
  500. /**
  501. * Return the translation to a specific week day
  502. *
  503. * @param int $day:
  504. * 0=sunday to 7=saturday (default numbers)
  505. * @param bool $abbr (if abbreviation should be returned)
  506. * @param offset: 0-6 (defaults to 0) [1 => 1=monday to 7=sunday]
  507. * @return string translatedText
  508. */
  509. public static function day($day, $abbr = false, $offset = 0) {
  510. $days = array(
  511. 'long' => array(
  512. 'Sunday',
  513. 'Monday',
  514. 'Tuesday',
  515. 'Wednesday',
  516. 'Thursday',
  517. 'Friday',
  518. 'Saturday'
  519. ),
  520. 'short' => array(
  521. 'Sun',
  522. 'Mon',
  523. 'Tue',
  524. 'Wed',
  525. 'Thu',
  526. 'Fri',
  527. 'Sat'
  528. )
  529. );
  530. $day = (int) $day;
  531. //pr($day);
  532. if ($offset) {
  533. $day = ($day + $offset) % 7;
  534. }
  535. //pr($day);
  536. if ($abbr) {
  537. return __($days['short'][$day]);
  538. }
  539. return __($days['long'][$day]);
  540. }
  541. /**
  542. * Return the translation to a specific week day
  543. *
  544. * @param int $month:
  545. * 1..12
  546. * @param bool $abbr (if abbreviation should be returned)
  547. * @param array $options
  548. * - appendDot (only for 3 letter abbr; defaults to false)
  549. * @return string translatedText
  550. */
  551. public static function month($month, $abbr = false, $options = array()) {
  552. $months = array(
  553. 'long' => array(
  554. 'January',
  555. 'February',
  556. 'March',
  557. 'April',
  558. 'May',
  559. 'June',
  560. 'July',
  561. 'August',
  562. 'September',
  563. 'October',
  564. 'November',
  565. 'December'
  566. ),
  567. 'short' => array(
  568. 'Jan',
  569. 'Feb',
  570. 'Mar',
  571. 'Apr',
  572. 'May',
  573. 'Jun',
  574. 'Jul',
  575. 'Aug',
  576. 'Sep',
  577. 'Oct',
  578. 'Nov',
  579. 'Dec'
  580. ),
  581. );
  582. $month = (int) ($month - 1);
  583. if (!$abbr) {
  584. return __($months['long'][$month]);
  585. }
  586. $monthName = __($months['short'][$month]);
  587. if (!empty($options['appendDot']) && strlen(__($months['long'][$month])) > 3) {
  588. $monthName .= '.';
  589. }
  590. return $monthName;
  591. }
  592. /**
  593. * Months
  594. *
  595. * @return array (for forms etc)
  596. */
  597. public static function months($monthKeys = array(), $options = array()) {
  598. if (!$monthKeys) {
  599. $monthKeys = range(1, 12);
  600. }
  601. $res = array();
  602. $abbr = isset($options['abbr']) ? $options['abbr'] : false;
  603. foreach ($monthKeys as $key) {
  604. $res[self::pad($key)] = self::month($key, $abbr, $options);
  605. }
  606. return $res;
  607. }
  608. /**
  609. * Weekdays
  610. *
  611. * @return array (for forms etc)
  612. */
  613. public static function days($dayKeys = array(), $options = array()) {
  614. if (!$dayKeys) {
  615. $dayKeys = range(0, 6);
  616. }
  617. $res = array();
  618. $abbr = isset($options['abbr']) ? $options['abbr'] : false;
  619. $offset = isset($options['offset']) ? $options['offset'] : 0;
  620. foreach ($dayKeys as $key) {
  621. $res[$key] = self::day($key, $abbr, $offset);
  622. }
  623. return $res;
  624. }
  625. /**
  626. * Returns the difference between a time and now in a "fuzzy" way.
  627. * Note that unlike [span], the "local" timestamp will always be the
  628. * current time. Displaying a fuzzy time instead of a date is usually
  629. * faster to read and understand.
  630. *
  631. * $span = fuzzy(time() - 10); // "moments ago"
  632. * $span = fuzzy(time() + 20); // "in moments"
  633. *
  634. * @param int "remote" timestamp
  635. * @return string
  636. */
  637. public static function fuzzy($timestamp) {
  638. // Determine the difference in seconds
  639. $offset = abs(time() - $timestamp);
  640. return self::fuzzyFromOffset($offset, $timestamp <= time());
  641. }
  642. /**
  643. * @param int $offset in seconds
  644. * @param bool $past (defaults to null: return plain text)
  645. * - new: if not boolean but a string use this as translating text
  646. * @return string text (i18n!)
  647. */
  648. public static function fuzzyFromOffset($offset, $past = null) {
  649. if ($offset <= MINUTE) {
  650. $span = 'moments';
  651. } elseif ($offset < (MINUTE * 20)) {
  652. $span = 'a few minutes';
  653. } elseif ($offset < HOUR) {
  654. $span = 'less than an hour';
  655. } elseif ($offset < (HOUR * 4)) {
  656. $span = 'a couple of hours';
  657. } elseif ($offset < DAY) {
  658. $span = 'less than a day';
  659. } elseif ($offset < (DAY * 2)) {
  660. $span = 'about a day';
  661. } elseif ($offset < (DAY * 4)) {
  662. $span = 'a couple of days';
  663. } elseif ($offset < WEEK) {
  664. $span = 'less than a week';
  665. } elseif ($offset < (WEEK * 2)) {
  666. $span = 'about a week';
  667. } elseif ($offset < MONTH) {
  668. $span = 'less than a month';
  669. } elseif ($offset < (MONTH * 2)) {
  670. $span = 'about a month';
  671. } elseif ($offset < (MONTH * 4)) {
  672. $span = 'a couple of months';
  673. } elseif ($offset < YEAR) {
  674. $span = 'less than a year';
  675. } elseif ($offset < (YEAR * 2)) {
  676. $span = 'about a year';
  677. } elseif ($offset < (YEAR * 4)) {
  678. $span = 'a couple of years';
  679. } elseif ($offset < (YEAR * 8)) {
  680. $span = 'a few years';
  681. } elseif ($offset < (YEAR * 12)) {
  682. $span = 'about a decade';
  683. } elseif ($offset < (YEAR * 24)) {
  684. $span = 'a couple of decades';
  685. } elseif ($offset < (YEAR * 64)) {
  686. $span = 'several decades';
  687. } else {
  688. $span = 'a long time';
  689. }
  690. if ($past === true) {
  691. // This is in the past
  692. return __('%s ago', __($span));
  693. }
  694. if ($past === false) {
  695. // This in the future
  696. return __('in %s', __($span));
  697. }
  698. if ($past !== null) {
  699. // Custom translation
  700. return __($past, __($span));
  701. }
  702. return __($span);
  703. }
  704. /**
  705. * Time length to human readable format.
  706. *
  707. * @param int $seconds
  708. * @param string format: format
  709. * @param options
  710. * - boolean v: verbose
  711. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  712. * - int: accuracy (how many sub-formats displayed?) //TODO
  713. * 2009-11-21 ms
  714. * @see timeAgoInWords()
  715. */
  716. public static function lengthOfTime($seconds, $format = null, $options = array()) {
  717. $defaults = array('verbose' => true, 'zero' => false, 'separator' => ', ', 'default' => '');
  718. $ret = '';
  719. $j = 0;
  720. $options = array_merge($defaults, $options);
  721. if (!$options['verbose']) {
  722. $s = array(
  723. 'm' => 'mth',
  724. 'd' => 'd',
  725. 'h' => 'h',
  726. 'i' => 'm',
  727. 's' => 's'
  728. );
  729. $p = $s;
  730. } else {
  731. $s = array(
  732. 'm' => ' ' . __('Month'), # translated
  733. 'd' => ' ' . __('Day'),
  734. 'h' => ' ' . __('Hour'),
  735. 'i' => ' ' . __('Minute'),
  736. 's' => ' ' . __('Second'),
  737. );
  738. $p = array(
  739. 'm' => ' ' . __('Months'), # translated
  740. 'd' => ' ' . __('Days'),
  741. 'h' => ' ' . __('Hours'),
  742. 'i' => ' ' . __('Minutes'),
  743. 's' => ' ' . __('Seconds'),
  744. );
  745. }
  746. if (!isset($format)) {
  747. //if (floor($seconds / MONTH) > 0) $format = 'Md';
  748. if (floor($seconds / DAY) > 0) $format = 'Dh';
  749. elseif (floor($seconds / 3600) > 0) $format = 'Hi';
  750. elseif (floor($seconds / 60) > 0) $format = 'Is';
  751. else $format = 'S';
  752. }
  753. for ($i = 0; $i < mb_strlen($format); $i++) {
  754. switch (mb_substr($format, $i, 1)) {
  755. case 'D':
  756. $str = floor($seconds / 86400);
  757. break;
  758. case 'd':
  759. $str = floor($seconds / 86400 % 30);
  760. break;
  761. case 'H':
  762. $str = floor($seconds / 3600);
  763. break;
  764. case 'h':
  765. $str = floor($seconds / 3600 % 24);
  766. break;
  767. case 'I':
  768. $str = floor($seconds / 60);
  769. break;
  770. case 'i':
  771. $str = floor($seconds / 60 % 60);
  772. break;
  773. case 'S':
  774. $str = $seconds;
  775. break;
  776. case 's':
  777. $str = floor($seconds % 60);
  778. break;
  779. default:
  780. return '';
  781. break;
  782. }
  783. if ($str > 0 || $j > 0 || $options['zero'] || $i == mb_strlen($format) - 1) {
  784. if ($j > 0) {
  785. $ret .= $options['separator'];
  786. }
  787. $j++;
  788. $x = mb_strtolower(mb_substr($format, $i, 1));
  789. if ($str == 1) {
  790. $ret .= $str . $s[$x];
  791. } else {
  792. $title = $p[$x];
  793. if (!empty($options['plural'])) {
  794. if (mb_substr($title, -1, 1) === 'e') {
  795. $title .= $options['plural'];
  796. }
  797. }
  798. $ret .= $str . $title;
  799. }
  800. }
  801. }
  802. return $ret;
  803. }
  804. /**
  805. * Time relative to NOW in human readable format - absolute (negative as well as positive)
  806. * //TODO: make "now" adjustable
  807. *
  808. * @param mixed $datestring
  809. * @param string format: format
  810. * @param options
  811. * - default, separator
  812. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  813. * - verbose/past/future: string with %s or boolean true/false
  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 = array_merge($defaults, $options);
  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. }