TimeLib.php 37 KB

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