TimeLib.php 35 KB

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