TimeLib.php 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  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 = 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 = static::age(mktime(0, 0, 0, 1, 1, $year));
  118. $minAge = static::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 = 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(array($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 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 = static::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 > static::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' . static::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 >= static::cweeks($year)) {
  294. return static::cweekBeginning($year + 1) - 1;
  295. }
  296. return static::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) : static::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 static::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 = static::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 = static::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[static::pad($key)] = static::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] = static::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 static::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. $ret = '';
  750. $j = 0;
  751. $length = mb_strlen($format);
  752. for ($i = 0; $i < $length; $i++) {
  753. switch (mb_substr($format, $i, 1)) {
  754. case 'D':
  755. $str = floor($seconds / 86400);
  756. break;
  757. case 'd':
  758. $str = floor($seconds / 86400 % 30);
  759. break;
  760. case 'H':
  761. $str = floor($seconds / 3600);
  762. break;
  763. case 'h':
  764. $str = floor($seconds / 3600 % 24);
  765. break;
  766. case 'I':
  767. $str = floor($seconds / 60);
  768. break;
  769. case 'i':
  770. $str = floor($seconds / 60 % 60);
  771. break;
  772. case 'S':
  773. $str = $seconds;
  774. break;
  775. case 's':
  776. $str = floor($seconds % 60);
  777. break;
  778. default:
  779. return '';
  780. break;
  781. }
  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() - static::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 = static::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 = static::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 = static::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 = static::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 = static::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] = static::pad($explode[$i]);
  946. }
  947. $explode[0] = static::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' ? static::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 = static::parseLocalizedDate($min);
  977. $max = static::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 = static::period($string, $options);
  990. return static::daysAsSql($period[0], $period[1], $fieldName);
  991. }
  992. /**
  993. * Hours, minutes
  994. * e.g. 9.3 => 9.5
  995. *
  996. * @param int $value
  997. * @return float
  998. */
  999. public static function standardToDecimalTime($value) {
  1000. $base = (int)$value;
  1001. $tmp = $value - $base;
  1002. $tmp *= 100;
  1003. $tmp *= 1 / 60;
  1004. $value = $base + $tmp;
  1005. return $value;
  1006. }
  1007. /**
  1008. * Hours, minutes
  1009. * e.g. 9.5 => 9.3
  1010. * with pad=2: 9.30
  1011. *
  1012. * @param int $value
  1013. * @param string $pad
  1014. * @param string $decPoint
  1015. * @return string
  1016. */
  1017. public static function decimalToStandardTime($value, $pad = null, $decPoint = '.') {
  1018. $base = (int)$value;
  1019. $tmp = $value - $base;
  1020. $tmp /= 1 / 60;
  1021. $tmp /= 100;
  1022. $value = $base + $tmp;
  1023. if ($pad === null) {
  1024. return $value;
  1025. }
  1026. return number_format($value, $pad, $decPoint, '');
  1027. }
  1028. /**
  1029. * Parse 2,5 - 2.5 2:30 2:31:58 or even 2011-11-12 10:10:10
  1030. * now supports negative values like -2,5 -2,5 -2:30 -:30 or -4
  1031. *
  1032. * @param string
  1033. * @param array $allowed
  1034. * @return int Seconds
  1035. */
  1036. public static function parseTime($duration, $allowed = array(':', '.', ',')) {
  1037. if (empty($duration)) {
  1038. return 0;
  1039. }
  1040. $parts = explode(' ', $duration);
  1041. $duration = array_pop($parts);
  1042. if (strpos($duration, '.') !== false && in_array('.', $allowed)) {
  1043. $duration = static::decimalToStandardTime($duration, 2, ':');
  1044. } elseif (strpos($duration, ',') !== false && in_array(',', $allowed)) {
  1045. $duration = str_replace(',', '.', $duration);
  1046. $duration = static::decimalToStandardTime($duration, 2, ':');
  1047. }
  1048. // now there is only the time schema left...
  1049. $pieces = explode(':', $duration, 3);
  1050. $res = 0;
  1051. $hours = abs((int)$pieces[0]) * HOUR;
  1052. //echo pre($hours);
  1053. $isNegative = (strpos((string)$pieces[0], '-') !== false ? true : false);
  1054. if (count($pieces) === 3) {
  1055. $res += $hours + ((int)$pieces[1]) * MINUTE + ((int)$pieces[2]) * SECOND;
  1056. } elseif (count($pieces) === 2) {
  1057. $res += $hours + ((int)$pieces[1]) * MINUTE;
  1058. } else {
  1059. $res += $hours;
  1060. }
  1061. if ($isNegative) {
  1062. return -$res;
  1063. }
  1064. return $res;
  1065. }
  1066. /**
  1067. * Parse 2022-11-12 or 12.11.2022 or even 12.11.22
  1068. *
  1069. * @param string $date
  1070. * @param array $allowed
  1071. * @return int Seconds
  1072. */
  1073. public static function parseDate($date, $allowed = array('.', '-')) {
  1074. $datePieces = explode(' ', $date, 2);
  1075. $date = array_shift($datePieces);
  1076. if (strpos($date, '.') !== false) {
  1077. $pieces = explode('.', $date);
  1078. $year = $pieces[2];
  1079. if (strlen($year) === 2) {
  1080. if ($year < 50) {
  1081. $year = '20' . $year;
  1082. } else {
  1083. $year = '19' . $year;
  1084. }
  1085. }
  1086. $date = mktime(0, 0, 0, $pieces[1], $pieces[0], $year);
  1087. } elseif (strpos($date, '-') !== false) {
  1088. //$pieces = explode('-', $date);
  1089. $date = strtotime($date);
  1090. } else {
  1091. return 0;
  1092. }
  1093. return $date;
  1094. }
  1095. /**
  1096. * Return strings like 2:30 (later //TODO: or 2:33:99) from seconds etc
  1097. *
  1098. * @param int $duraton Duraction in seconds
  1099. * @param string $mode
  1100. * @return string Time
  1101. */
  1102. public static function buildTime($duration, $mode = 'H:MM') {
  1103. if ($duration < 0) {
  1104. $duration = abs($duration);
  1105. $isNegative = true;
  1106. }
  1107. $minutes = $duration % HOUR;
  1108. $hours = ($duration - $minutes) / HOUR;
  1109. $res = (int)$hours . ':' . static::pad(intval($minutes / MINUTE));
  1110. if (strpos($mode, 'SS') !== false) {
  1111. //TODO
  1112. }
  1113. if (!empty($isNegative)) {
  1114. $res = '-' . $res;
  1115. }
  1116. return $res;
  1117. }
  1118. /**
  1119. * Return strings like 2:33:99 from seconds etc
  1120. *
  1121. * @param int $duration Duration in seconds
  1122. * @return string Time
  1123. */
  1124. public static function buildDefaultTime($duration) {
  1125. $minutes = $duration % HOUR;
  1126. $duration = $duration - $minutes;
  1127. $hours = $duration / HOUR;
  1128. $seconds = $minutes % MINUTE;
  1129. return static::pad($hours) . ':' . static::pad($minutes / MINUTE) . ':' . static::pad($seconds / SECOND);
  1130. }
  1131. /**
  1132. * TimeLib::pad()
  1133. *
  1134. * @param string $value
  1135. * @param int $length
  1136. * @param string $string
  1137. * @return string
  1138. */
  1139. public static function pad($value, $length = 2, $string = '0') {
  1140. return str_pad(intval($value), $length, $string, STR_PAD_LEFT);
  1141. }
  1142. /**
  1143. * EXPERIMENTAL!!!
  1144. *
  1145. * @param int $gmtoffset Offset in seconds
  1146. * @param bool $isDst If DST
  1147. * @return int offset Calculated offset
  1148. */
  1149. public static function tzOffset($gmtoffset, $isDst) {
  1150. extract(getdate());
  1151. $serveroffset = gmmktime(0, 0, 0, $mon, $mday, $year) - mktime(0, 0, 0, $mon, $mday, $year);
  1152. $offset = $gmtoffset - $serveroffset;
  1153. return $offset + ($isDst ? 3600 : 0);
  1154. }
  1155. }