TimeLib.php 38 KB

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