TimeLib.php 37 KB

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