TimeLib.php 37 KB

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