TimeLib.php 35 KB

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