TimeLib.php 35 KB

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