TimeLib.php 36 KB

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