TimeLib.php 36 KB

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