TimeLib.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316
  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. * - userOffset: User's offset from GMT (in hours)
  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'=>'-----', 'userOffset'=>null);
  370. $options = array_merge($defaults, $options);
  371. $date = null;
  372. if ($dateString !== null) {
  373. $date = self::fromString($dateString, $options['userOffset']);
  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. $res = strftime($format, $date);
  386. if (WINDOWS) {
  387. $res = utf8_encode($res);
  388. }
  389. return $res;
  390. }
  391. /**
  392. * outputs Date(time) Sting nicely formatted
  393. * @param string $dateString,
  394. * @param string $format (YYYY-MM-DD, DD.MM.YYYY)
  395. * @param array $options
  396. * - userOffset: User's offset from GMT (in hours)
  397. * - default (defaults to "-----")
  398. * 2009-03-31 ms
  399. */
  400. public static function niceDate($dateString = null, $format = null, $options = array()) {
  401. $defaults = array('default'=>'-----', 'userOffset'=>null);
  402. $options = array_merge($defaults, $options);
  403. $date = null;
  404. if ($dateString !== null) {
  405. $date = self::fromString($dateString, $options['userOffset']);
  406. }
  407. if ($date === null || $date === false || $date <= 0) {
  408. return $options['default'];
  409. }
  410. if ($format === null) {
  411. if (is_int($dateString) || strpos($dateString, ' ') !== false) {
  412. $format = FORMAT_NICE_YMDHM;
  413. } else {
  414. $format = FORMAT_NICE_YMD;
  415. }
  416. }
  417. $ret = date($format, $date);
  418. if (!empty($options['oclock']) && $options['oclock']) {
  419. switch ($format) {
  420. case FORMAT_NICE_YMDHM:
  421. case FORMAT_NICE_YMDHMS:
  422. case FORMAT_NICE_YMDHM:
  423. case FORMAT_NICE_HM:
  424. case FORMAT_NICE_HMS:
  425. $ret .= ' '.__('o\'clock');
  426. break;
  427. }
  428. }
  429. return $ret;
  430. }
  431. /**
  432. * return the translation to a specific week day
  433. * @param int $day:
  434. * 0=sunday to 7=saturday (default numbers)
  435. * @param bool $abbr (if abbreviation should be returned)
  436. * @param offset: 0-6 (defaults to 0) [1 => 1=monday to 7=sunday]
  437. * @return string $translatedText
  438. * 2011-12-07 ms
  439. */
  440. public static function day($day, $abbr = false, $offset = 0) {
  441. $days = array(
  442. 'long' => array(
  443. 'Sunday',
  444. 'Monday',
  445. 'Tuesday',
  446. 'Wednesday',
  447. 'Thursday',
  448. 'Friday',
  449. 'Saturday'
  450. ),
  451. 'short' => array(
  452. 'Sun',
  453. 'Mon',
  454. 'Tue',
  455. 'Wed',
  456. 'Thu',
  457. 'Fri',
  458. 'Sat'
  459. )
  460. );
  461. $day = (int) $day;
  462. pr($day);
  463. if ($offset) {
  464. $day = ($day + $offset) % 7;
  465. }
  466. pr($day);
  467. if ($abbr) {
  468. return __($days['short'][$day]);
  469. }
  470. return __($days['long'][$day]);
  471. }
  472. /**
  473. * return the translation to a specific week day
  474. * @param int $month:
  475. * 1..12
  476. * @param bool $abbr (if abbreviation should be returned)
  477. * @param array $options
  478. * - appendDot (only for 3 letter abbr; defaults to false)
  479. * @return string $translatedText
  480. * 2011-12-07 ms
  481. */
  482. public static function month($month, $abbr = false, $options = array()) {
  483. $months = array(
  484. 'long' => array(
  485. 'January',
  486. 'February',
  487. 'March',
  488. 'April',
  489. 'May',
  490. 'June',
  491. 'July',
  492. 'August',
  493. 'September',
  494. 'October',
  495. 'November',
  496. 'December'
  497. ),
  498. 'short' => array(
  499. 'Jan',
  500. 'Feb',
  501. 'Mar',
  502. 'Apr',
  503. 'May',
  504. 'Jun',
  505. 'Jul',
  506. 'Aug',
  507. 'Sep',
  508. 'Oct',
  509. 'Nov',
  510. 'Dec'
  511. ),
  512. );
  513. $month = (int) ($month - 1);
  514. if (!$abbr) {
  515. return __($months['long'][$month]);
  516. }
  517. $monthName = __($months['short'][$month]);
  518. if (!empty($options['appendDot']) && strlen(__($months['long'][$month])) > 3) {
  519. $monthName .= '.';
  520. }
  521. return $monthName;
  522. }
  523. /**
  524. * @return array (for forms etc)
  525. */
  526. public static function months($monthKeys = array(), $options = array()) {
  527. if (!$monthKeys) {
  528. $monthKeys = range(1, 12);
  529. }
  530. $res = array();
  531. $abbr = isset($options['abbr']) ? $options['abbr'] : false;
  532. foreach ($monthKeys as $key) {
  533. $res[str_pad($key, 2, '0', STR_PAD_LEFT)] = self::month($key, $abbr, $options);
  534. }
  535. return $res;
  536. }
  537. /**
  538. * weekdays
  539. * @return array (for forms etc)
  540. */
  541. public static function days($dayKeys = array(), $options = array()) {
  542. if (!$dayKeys) {
  543. $dayKeys = range(0, 6);
  544. }
  545. $res = array();
  546. $abbr = isset($options['abbr']) ? $options['abbr'] : false;
  547. $offset = isset($options['offset']) ? $options['offset'] : 0;
  548. foreach ($dayKeys as $key) {
  549. $res[$key] = self::day($key, $abbr, $offset);
  550. }
  551. return $res;
  552. }
  553. /**
  554. * can convert time from one unit to another
  555. * @param int INT | time
  556. * @param from CHAR
  557. * @param to CHAR
  558. * @param options: acc=>INT [accuracy], showZero=>BOOL, returnArray=>BOOL
  559. * 2008-11-06 ms
  560. */
  561. public static function convertTime($int, $from, $to, $options = array()) {
  562. $accuracy = 0; # 0 = only the "to"-element, 1..n = higher accurancy
  563. $showZero = false; # show only the non-zero elements
  564. $returnArray = false; # return as array instead of as string
  565. if (!empty($options)) {
  566. if (isset($options['acc'])) {
  567. $accuracy = (int)$options['acc'];
  568. }
  569. if (isset($options['showZero'])) {
  570. $showZero = (int)$options['showZero'];
  571. }
  572. if (isset($options['returnArray'])) {
  573. $return = ($options['returnArray']===true?true:false);
  574. }
  575. }
  576. $times = array(
  577. 's'=>'0',
  578. 'm'=>'1',
  579. 'h'=>'2',
  580. 'd'=>'3',
  581. 'w'=>'4',
  582. 'm'=>'5',
  583. 'y'=>'6',
  584. );
  585. $options = array(
  586. '0'=>array(
  587. 'steps'=>array('1'=>60,'2'=>3600,'3'=>86400,'4'=>86400*7,'5'=>86400*30,'6'=>86400*365),
  588. 'down'=>0,
  589. 'up'=>60,
  590. 'short'=>'s',
  591. 'long'=>'seconds'
  592. ),
  593. '1'=>array(
  594. 'steps'=>array('0'=>60,'2'=>60,'3'=>60*24,'4'=>60*24*7,'5'=>60*24*30,'6'=>60*24*365),
  595. 'down'=>60,
  596. 'up'=>60,
  597. 'short'=>'m',
  598. 'long'=>'minutes'
  599. ),
  600. '2'=>array(
  601. 'steps'=>array('0'=>3600,'1'=>60,'3'=>24,'4'=>24*7,'5'=>24*30,'6'=>24*365),
  602. 'down'=>60,
  603. 'up'=>24,
  604. 'short'=>'h',
  605. 'long'=>'hours'
  606. ),
  607. '3'=>array(
  608. 'steps'=>array('0'=>86400,'1'=>3600,'2'=>24,'4'=>7,'5'=>30,'6'=>365),
  609. 'down'=>24,
  610. 'up'=>7,
  611. 'short'=>'d',
  612. 'long'=>'days'
  613. ),
  614. '4'=>array(
  615. 'steps'=>array('0'=>86400*7,'1'=>60*24*7,'2'=>24*7,'3'=>7,'5'=>4.2,'6'=>52),
  616. 'down'=>7,
  617. 'up'=>4.2,
  618. 'short'=>'w',
  619. 'long'=>'weeks'
  620. ),
  621. '5'=>array(
  622. 'steps'=>array('0'=>86400*30,'1'=>60*24*30,'2'=>24*30,'3'=>30,'4'=>4.2,'6'=>12),
  623. 'down'=>4.2,
  624. 'up'=>12,
  625. 'short'=>'m',
  626. 'long'=>'months'
  627. ),
  628. '6'=>array(
  629. 'steps'=>array('0'=>86400*365,'1'=>60*24*365,'2'=>24*365,'3'=>365,'4'=>52,'5'=>12),
  630. 'down'=>12,
  631. 'up'=>0,
  632. 'short'=>'y',
  633. 'long'=>'years'
  634. ),
  635. );
  636. //echo $options[0]['steps']['4'];
  637. if (array_key_exists($from, $times) && array_key_exists($to, $times)) {
  638. $begin = $times[$from];
  639. $end = $times[$to];
  640. //echo $begin-$end.BR;
  641. }
  642. $minuten = $int;
  643. if ($minuten<60) {
  644. return $minuten.'min';
  645. }
  646. $calculated = floor($minuten/60)."h ".($minuten%60)."min";
  647. if ($returnArray) {
  648. // return as array
  649. } else {
  650. // convert to the desired string
  651. }
  652. return $calculated;
  653. }
  654. /**
  655. * @deprecated
  656. * NICHT TESTEN!
  657. */
  658. public static function otherOne() {
  659. $day = floor($anz_sekunden/86400);
  660. $hours = floor(($anz_sekunden-(floor($anz_sekunden/86400)*86400))/3600);
  661. $minutes = floor(($anz_sekunden-(floor($anz_sekunden/3600)*3600))/60);
  662. $seconds = floor($anz_sekunden-(floor($anz_sekunden/60))*60);
  663. if ($day < 10) {
  664. $day = '0'.$day;
  665. }
  666. if ($hours < 10) {
  667. $hours = '0'.$hours;
  668. }
  669. if ($minutes < 10) {
  670. $minutes = '0'.$minutes;
  671. }
  672. if ($seconds < 10) {
  673. $seconds = '0'.$seconds;
  674. }
  675. if ($day > 0) {
  676. $zeit_ausgabe = $day.":".$hours.":".$minutes.":".$seconds;
  677. } else {
  678. $zeit_ausgabe = $hours.":".$minutes.":".$seconds." h";
  679. }
  680. }
  681. /**
  682. * Returns the difference between a time and now in a "fuzzy" way.
  683. * Note that unlike [span], the "local" timestamp will always be the
  684. * current time. Displaying a fuzzy time instead of a date is usually
  685. * faster to read and understand.
  686. *
  687. * $span = fuzzy(time() - 10); // "moments ago"
  688. * $span = fuzzy(time() + 20); // "in moments"
  689. *
  690. * @param integer "remote" timestamp
  691. * @return string
  692. */
  693. public static function fuzzy($timestamp) {
  694. // Determine the difference in seconds
  695. $offset = abs(time() - $timestamp);
  696. return self::fuzzyFromOffset($offset, $timestamp <= time());
  697. }
  698. /**
  699. * @param int $offset in seconds
  700. * @param boolean $past (defaults to null: return plain text)
  701. * - new: if not boolean but a string use this as translating text
  702. * @return string $text (i18n!)
  703. * 2011-03-06 ms
  704. */
  705. public static function fuzzyFromOffset($offset, $past = null) {
  706. if ($offset <= MINUTE) {
  707. $span = 'moments';
  708. } elseif ($offset < (MINUTE * 20)) {
  709. $span = 'a few minutes';
  710. } elseif ($offset < HOUR) {
  711. $span = 'less than an hour';
  712. } elseif ($offset < (HOUR * 4)) {
  713. $span = 'a couple of hours';
  714. } elseif ($offset < DAY) {
  715. $span = 'less than a day';
  716. } elseif ($offset < (DAY * 2)) {
  717. $span = 'about a day';
  718. } elseif ($offset < (DAY * 4)) {
  719. $span = 'a couple of days';
  720. } elseif ($offset < WEEK) {
  721. $span = 'less than a week';
  722. } elseif ($offset < (WEEK * 2)) {
  723. $span = 'about a week';
  724. } elseif ($offset < MONTH) {
  725. $span = 'less than a month';
  726. } elseif ($offset < (MONTH * 2)) {
  727. $span = 'about a month';
  728. } elseif ($offset < (MONTH * 4)) {
  729. $span = 'a couple of months';
  730. } elseif ($offset < YEAR) {
  731. $span = 'less than a year';
  732. } elseif ($offset < (YEAR * 2)) {
  733. $span = 'about a year';
  734. } elseif ($offset < (YEAR * 4)) {
  735. $span = 'a couple of years';
  736. } elseif ($offset < (YEAR * 8)) {
  737. $span = 'a few years';
  738. } elseif ($offset < (YEAR * 12)) {
  739. $span = 'about a decade';
  740. } elseif ($offset < (YEAR * 24)) {
  741. $span = 'a couple of decades';
  742. } elseif ($offset < (YEAR * 64)) {
  743. $span = 'several decades';
  744. } else {
  745. $span = 'a long time';
  746. }
  747. if ($past === true) {
  748. // This is in the past
  749. return __('%s ago', __($span));
  750. } elseif ($past === false) {
  751. // This in the future
  752. return __('in %s', __($span));
  753. } elseif ($past !== null) {
  754. // Custom translation
  755. return __($past, __($span));
  756. }
  757. return __($span);
  758. }
  759. /**
  760. * time length to human readable format
  761. * @param int $seconds
  762. * @param string format: format
  763. * @param options
  764. * - boolean v: verbose
  765. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  766. * - int: accuracy (how many sub-formats displayed?) //TODO
  767. * 2009-11-21 ms
  768. * @see timeAgoInWords()
  769. */
  770. public static function lengthOfTime($seconds, $format = null, $options = array()) {
  771. $defaults = array('verbose'=>true, 'zero'=>false, 'separator'=>', ', 'default'=>'');
  772. $ret = '';
  773. $j = 0;
  774. $options = array_merge($defaults, $options);
  775. if (!$options['verbose']) {
  776. $s = array(
  777. 'm' => 'mth',
  778. 'd' => 'd',
  779. 'h' => 'h',
  780. 'i' => 'm',
  781. 's' => 's'
  782. );
  783. $p = $s;
  784. } else {
  785. $s = array(
  786. 'm' => ' '.__('Month'), # translated
  787. 'd' => ' '.__('Day'),
  788. 'h' => ' '.__('Hour'),
  789. 'i' => ' '.__('Minute'),
  790. 's' => ' '.__('Second'),
  791. );
  792. $p = array (
  793. 'm' => ' '.__('Months'), # translated
  794. 'd' => ' '.__('Days'),
  795. 'h' => ' '.__('Hours'),
  796. 'i' => ' '.__('Minutes'),
  797. 's' => ' '.__('Seconds'),
  798. );
  799. }
  800. if (!isset($format)) {
  801. //if (floor($seconds / MONTH) > 0) $format = "Md";
  802. if (floor($seconds / DAY) > 0) $format = "Dh";
  803. elseif (floor($seconds / 3600) > 0) $format = "Hi";
  804. elseif (floor($seconds / 60) > 0) $format = "Is";
  805. else $format = "S";
  806. }
  807. for ($i = 0; $i < mb_strlen($format); $i++) {
  808. switch (mb_substr($format, $i, 1)) {
  809. case 'D':
  810. $str = floor($seconds / 86400);
  811. break;
  812. case 'd':
  813. $str = floor($seconds / 86400 % 30);
  814. break;
  815. case 'H':
  816. $str = floor($seconds / 3600);
  817. break;
  818. case 'h':
  819. $str = floor($seconds / 3600 % 24);
  820. break;
  821. case 'I':
  822. $str = floor($seconds / 60);
  823. break;
  824. case 'i':
  825. $str = floor($seconds / 60 % 60);
  826. break;
  827. case 'S':
  828. $str = $seconds;
  829. break;
  830. case 's':
  831. $str = floor($seconds % 60);
  832. break;
  833. default:
  834. return "";
  835. break;
  836. }
  837. if ($str > 0 || $j > 0 || $options['zero'] || $i == mb_strlen($format) - 1) {
  838. if ($j>0) {
  839. $ret .= $options['separator'];
  840. }
  841. $j++;
  842. $x = mb_strtolower(mb_substr($format, $i, 1));
  843. if ($str == 1) {
  844. $ret .= $str . $s[$x];
  845. } else {
  846. $title = $p[$x];
  847. if (!empty($options['plural'])) {
  848. if (mb_substr($title, -1, 1) == 'e') {
  849. $title .= $options['plural'];
  850. }
  851. }
  852. $ret .= $str . $title;
  853. }
  854. }
  855. }
  856. return $ret;
  857. }
  858. /**
  859. * time relative to NOW in human readable format - absolute (negative as well as positive)
  860. * //TODO: make "now" adjustable
  861. * @param mixed $datestring
  862. * @param string format: format
  863. * @param options
  864. * - default, separator
  865. * - boolean zero: if false: 0 days 5 hours => 5 hours etc.
  866. * - verbose/past/future: string with %s or boolean true/false
  867. * 2009-11-21 ms
  868. */
  869. public static function relLengthOfTime($dateString, $format = null, $options = array()) {
  870. if ($dateString != null) {
  871. $userOffset = null;
  872. $sec = time() - self::fromString($dateString, $userOffset);
  873. $type = ($sec > 0)?-1:(($sec < 0)?1:0);
  874. $sec = abs($sec);
  875. } else {
  876. $sec = 0;
  877. $type = 0;
  878. }
  879. $defaults = array('verbose'=>__('justNow'), 'zero'=>false,'separator'=>', ', 'future'=>__('In %s'), 'past'=>__('%s ago'),'default'=>'');
  880. $options = array_merge($defaults, $options);
  881. $ret = self::lengthOfTime($sec, $format, $options);
  882. if ($type == 1) {
  883. if ($options['future'] !== false) {
  884. return sprintf($options['future'], $ret);
  885. }
  886. return array('future'=>$ret);
  887. } elseif ($type == -1) {
  888. if ($options['past'] !== false) {
  889. return sprintf($options['past'], $ret);
  890. }
  891. return array('past'=>$ret);
  892. } else {
  893. if ($options['verbose'] !== false) {
  894. return $options['verbose'];
  895. }
  896. //return array('now'=>true);
  897. }
  898. return $options['default'];
  899. }
  900. /**
  901. * Returns true if given datetime string was day before yesterday.
  902. *
  903. * @param string $dateString Datetime string or Unix timestamp
  904. * @param int $userOffset User's offset from GMT (in hours)
  905. * @return boolean True if datetime string was day before yesterday
  906. */
  907. public static function wasDayBeforeYesterday($dateString, $userOffset = null) {
  908. $date = self::fromString($dateString, $userOffset);
  909. return date(FORMAT_DB_DATE, $date) == date(FORMAT_DB_DATE, time()-2*DAY);
  910. }
  911. /**
  912. * Returns true if given datetime string is the day after tomorrow.
  913. *
  914. * @param string $dateString Datetime string or Unix timestamp
  915. * @param int $userOffset User's offset from GMT (in hours)
  916. * @return boolean True if datetime string is day after tomorrow
  917. */
  918. public static function isDayAfterTomorrow($dateString, $userOffset = null) {
  919. $date = self::fromString($dateString, $userOffset);
  920. return date(FORMAT_DB_DATE, $date) == date(FORMAT_DB_DATE, time()+2*DAY);
  921. }
  922. /**
  923. * Returns true if given datetime string is not today AND is in the future.
  924. *
  925. * @param string $dateString Datetime string or Unix timestamp
  926. * @param int $userOffset User's offset from GMT (in hours)
  927. * @return boolean True if datetime is not today AND is in the future
  928. */
  929. public static function isNotTodayAndInTheFuture($dateString, $userOffset = null) {
  930. $date = self::fromString($dateString, $userOffset);
  931. return date(FORMAT_DB_DATE, $date) > date(FORMAT_DB_DATE, time());
  932. }
  933. /**
  934. * Returns true if given datetime string is not now AND is in the future.
  935. *
  936. * @param string $dateString Datetime string or Unix timestamp
  937. * @param int $userOffset User's offset from GMT (in hours)
  938. * @return boolean True if datetime is not today AND is in the future
  939. */
  940. public static function isInTheFuture($dateString, $userOffset = null) {
  941. $date = self::fromString($dateString, $userOffset);
  942. return date(FORMAT_DB_DATETIME, $date) > date(FORMAT_DB_DATETIME, time());
  943. }
  944. /**
  945. * try to parse date from various input formats
  946. * - DD.MM.YYYY, DD/MM/YYYY, YYYY-MM-DD, YYYY, YYYY-MM, ...
  947. * - i18n: Today, Yesterday, Tomorrow
  948. * @param string $date to parse
  949. * @param format to parse (null = auto)
  950. * @param type
  951. * - start: first second of this interval
  952. * - end: last second of this interval
  953. * @return int timestamp
  954. * 2011-11-19 ms
  955. */
  956. public static function parseLocalizedDate($date, $format = null, $type = 'start') {
  957. $date = trim($date);
  958. echo returns($date);
  959. $i18n = array(
  960. 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')))),
  961. 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)),
  962. 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)),
  963. 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)),
  964. 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)),
  965. );
  966. if (isset($i18n[strtolower($date)])) {
  967. return $i18n[strtolower($date)][$type];
  968. }
  969. if ($format) {
  970. $res = DateTime::createFromFormat($format, $date);
  971. $res = $res->format(FORMAT_DB_DATE).' '.($type=='end'?'23:59:59':'00:00:00');
  972. return $res;
  973. }
  974. if (strpos($date, '.') !== false) {
  975. $explode = explode('.', $date, 3);
  976. $explode = array_reverse($explode);
  977. } elseif (strpos($date, '/') !== false) {
  978. $explode = explode('/', $date, 3);
  979. $explode = array_reverse($explode);
  980. } elseif (strpos($date, '-') !== false) {
  981. $explode = explode('-', $date, 3);
  982. } else {
  983. $explode = array($date);
  984. }
  985. if (isset($explode)) {
  986. for ($i = 0; $i < count($explode); $i++) {
  987. $explode[$i] = str_pad($explode[$i], 2, '0', STR_PAD_LEFT);
  988. }
  989. $explode[0] = str_pad($explode[0], 4, '20', STR_PAD_LEFT);
  990. if (count($explode) === 3) {
  991. return implode('-', $explode).' '.($type=='end'?'23:59:59':'00:00:00');
  992. } elseif (count($explode) === 2) {
  993. return implode('-', $explode).'-'.($type=='end'?self::daysInMonth($explode[0], $explode[1]):'01').' '.($type=='end'?'23:59:59':'00:00:00');
  994. } else {
  995. return $explode[0].'-'.($type=='end'?'12':'01').'-'.($type=='end'?'31':'01').' '.($type=='end'?'23:59:59':'00:00:00');
  996. }
  997. }
  998. return false;
  999. }
  1000. /**
  1001. * @param string $searchString to parse
  1002. * @param array $options
  1003. * - separator (defaults to space [ ])
  1004. * - format (defaults to Y-m-d H:i:s)
  1005. * @return array $period [0=>min, 1=>max]
  1006. * 2011-11-18 ms
  1007. */
  1008. public static function period($string, $options = array()) {
  1009. if (strpos($string, ' ') !== false) {
  1010. $filters = explode(' ', $string);
  1011. $filters = array(array_shift($filters), array_pop($filters));
  1012. } else {
  1013. $filters = array($string, $string);
  1014. }
  1015. $min = $filters[0];
  1016. $max = $filters[1];
  1017. //$x = preg_match('/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/', $date, $date_parts);
  1018. //$x = Datetime::createFromFormat('Y-m-d', $string);
  1019. //die(returns($x));
  1020. //$actualDateTime = new DateTime($min);
  1021. //$actualDateTime->add(new DateInterval('P1M'));
  1022. $min = self::parseLocalizedDate($min);
  1023. $max = self::parseLocalizedDate($max, null, 'end');
  1024. //die($actualDateTime->format('Y-m-d'));
  1025. //$searchParameters['conditions']['Coupon.date'] = $actualDateTime->format('Y-m-d');
  1026. /*
  1027. if ($min == $max) {
  1028. if (strlen($max) > 8) {
  1029. $max = date(FORMAT_DB_DATE, strtotime($max)+DAY);
  1030. } elseif (strlen($max) > 5) {
  1031. $max = date(FORMAT_DB_DATE, strtotime($max)+MONTH);
  1032. } else {
  1033. $max = date(FORMAT_DB_DATE, strtotime($max)+YEAR+MONTH);
  1034. }
  1035. }
  1036. $min = date(FORMAT_DB_DATE, strtotime($min));
  1037. $max = date(FORMAT_DB_DATE, strtotime($max));
  1038. */
  1039. return array($min, $max);
  1040. }
  1041. /**
  1042. * @param string $searchString to parse
  1043. * @param string $fieldname (Model.field)
  1044. * @param array $options (see TimeLib::period)
  1045. * @return string $query SQL Query
  1046. * 2011-11-18 ms
  1047. */
  1048. public static function periodAsSql($string, $fieldName, $options = array()) {
  1049. $period = self::period($string, $options);
  1050. return self::daysAsSql($period[0], $period[1], $fieldName);
  1051. }
  1052. /**
  1053. * hours, minutes
  1054. * e.g. 9.3 => 9.5
  1055. * 2010-11-03 ms
  1056. */
  1057. public static function standardToDecimalTime($value) {
  1058. $base = (int)$value;
  1059. $tmp = $value-$base;
  1060. $tmp *= 100;
  1061. $tmp *= 1/60;
  1062. $value = $base+$tmp;
  1063. return $value;
  1064. }
  1065. /**
  1066. * hours, minutes
  1067. * e.g. 9.5 => 9.3
  1068. * with pad=2: 9.30
  1069. * 2010-11-03 ms
  1070. */
  1071. public static function decimalToStandardTime($value, $pad = null, $decPoint = '.') {
  1072. $base = (int)$value;
  1073. $tmp = $value-$base;
  1074. $tmp /= 1/60;
  1075. $tmp /= 100;
  1076. $value = $base+$tmp;
  1077. if ($pad === null) {
  1078. return $value;
  1079. }
  1080. return number_format($value, $pad, $decPoint, '');
  1081. }
  1082. /**
  1083. * parse 2,5 - 2.5 2:30 2:31:58 or even 2011-11-12 10:10:10
  1084. * now supports negative values like -2,5 -2,5 -2:30 -:30 or -4
  1085. * @param string
  1086. * @return int: seconds
  1087. * 2011-03-06 ms
  1088. */
  1089. public static function parseTime($duration, $allowed = array(':', '.', ',')) {
  1090. if (empty($duration)) {
  1091. return 0;
  1092. }
  1093. $parts = explode(' ', $duration);
  1094. $duration = array_pop($parts);
  1095. if (strpos($duration, '.') !== false && in_array('.', $allowed)) {
  1096. $duration = self::decimalToStandardTime($duration, 2, ':');
  1097. } elseif (strpos($duration, ',') !== false && in_array(',', $allowed)) {
  1098. $duration = str_replace(',', '.', $duration);
  1099. $duration = self::decimalToStandardTime($duration, 2, ':');
  1100. }
  1101. # now there is only the time schema left...
  1102. $pieces = explode(':', $duration, 3);
  1103. $res = 0;
  1104. $hours = abs((int)$pieces[0])*HOUR;
  1105. //echo pre($hours);
  1106. $isNegative = (strpos((string)$pieces[0], '-') !== false ? true : false);
  1107. if (count($pieces) === 3) {
  1108. $res += $hours + ((int)$pieces[1])*MINUTE + ((int)$pieces[2])*SECOND;
  1109. } elseif (count($pieces) === 2) {
  1110. $res += $hours + ((int)$pieces[1])*MINUTE;
  1111. } else {
  1112. $res += $hours;
  1113. }
  1114. if ($isNegative) {
  1115. return -$res;
  1116. }
  1117. return $res;
  1118. }
  1119. /**
  1120. * parse 2022-11-12 or 12.11.2022 or even 12.11.22
  1121. * @param string $date
  1122. * @return int: seconds
  1123. * 2011-03-09 ms
  1124. */
  1125. public static function parseDate($date, $allowed = array('.', '-')) {
  1126. $datePieces = explode(' ', $date, 2);
  1127. $date = array_shift($datePieces);
  1128. if (strpos($date, '.') !== false) {
  1129. $pieces = explode('.', $date);
  1130. $year = $pieces[2];
  1131. if (strlen($year) === 2) {
  1132. if ($year < 50) {
  1133. $year = '20'.$year;
  1134. } else {
  1135. $year = '19'.$year;
  1136. }
  1137. }
  1138. $date = mktime(0, 0, 0, $pieces[1], $pieces[0], $year);
  1139. } elseif (strpos($date, '-') !== false) {
  1140. //$pieces = explode('-', $date);
  1141. $date = strtotime($date);
  1142. } else {
  1143. return 0;
  1144. }
  1145. return $date;
  1146. }
  1147. /**
  1148. * return strings like 2:30 (later //TODO: or 2:33:99) from seconds etc
  1149. * @param int: seconds
  1150. * @return string
  1151. * 2011-03-06 ms
  1152. */
  1153. public static function buildTime($duration, $mode = 'H:MM') {
  1154. if ($duration < 0) {
  1155. $duration = abs($duration);
  1156. $isNegative = true;
  1157. }
  1158. $minutes = $duration%HOUR;
  1159. $hours = ($duration - $minutes)/HOUR;
  1160. $res = (int)$hours.':'.str_pad(intval($minutes/MINUTE), 2, '0', STR_PAD_LEFT);
  1161. if (strpos($mode, 'SS') !== false) {
  1162. //TODO
  1163. }
  1164. if (!empty($isNegative)) {
  1165. $res = '-'.$res;
  1166. }
  1167. return $res;
  1168. }
  1169. /**
  1170. * return strings like 2:33:99 from seconds etc
  1171. * @param int: seconds
  1172. * @return string
  1173. * 2011-03-09 ms
  1174. */
  1175. public static function buildDefaultTime($duration) {
  1176. $minutes = $duration%HOUR;
  1177. $duration = $duration - $minutes;
  1178. $hours = ($duration)/HOUR;
  1179. //$duration = $minutes*MINUTE;
  1180. $seconds = $minutes%MINUTE;
  1181. return self::pad($hours).':'.self::pad($minutes/MINUTE).':'.self::pad($seconds/SECOND);
  1182. }
  1183. public static function pad($value, $length = 2) {
  1184. return str_pad(intval($value), $length, '0', STR_PAD_LEFT);
  1185. }
  1186. }