TimeLib.php 37 KB

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