TimeLib.php 37 KB

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