TimeLib.php 38 KB

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