TimeLib.php 38 KB

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