Merge pull request #15578 from mattwire/redundant_format
[civicrm-core.git] / CRM / Utils / Date.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 */
33
34 /**
35 * Date utilties
36 */
37 class CRM_Utils_Date {
38
39 /**
40 * Format a date by padding it with leading '0'.
41 *
42 * @param array $date
43 * ('Y', 'M', 'd').
44 * @param string $separator
45 * The seperator to use when formatting the date.
46 * @param int|string $invalidDate what to return if the date is invalid
47 *
48 * @return string
49 * formatted string for date
50 */
51 public static function format($date, $separator = '', $invalidDate = 0) {
52 if (is_numeric($date) &&
53 ((strlen($date) == 8) || (strlen($date) == 14))
54 ) {
55 return $date;
56 }
57
58 if (!is_array($date) ||
59 CRM_Utils_System::isNull($date) ||
60 empty($date['Y'])
61 ) {
62 return $invalidDate;
63 }
64
65 $date['Y'] = (int ) $date['Y'];
66 if ($date['Y'] < 1000 || $date['Y'] > 2999) {
67 return $invalidDate;
68 }
69
70 if (array_key_exists('m', $date)) {
71 $date['M'] = $date['m'];
72 }
73 elseif (array_key_exists('F', $date)) {
74 $date['M'] = $date['F'];
75 }
76
77 if (!empty($date['M'])) {
78 $date['M'] = (int ) $date['M'];
79 if ($date['M'] < 1 || $date['M'] > 12) {
80 return $invalidDate;
81 }
82 }
83 else {
84 $date['M'] = 1;
85 }
86
87 if (!empty($date['d'])) {
88 $date['d'] = (int ) $date['d'];
89 }
90 else {
91 $date['d'] = 1;
92 }
93
94 if (!checkdate($date['M'], $date['d'], $date['Y'])) {
95 return $invalidDate;
96 }
97
98 $date['M'] = sprintf('%02d', $date['M']);
99 $date['d'] = sprintf('%02d', $date['d']);
100
101 $time = '';
102 if (CRM_Utils_Array::value('H', $date) != NULL ||
103 CRM_Utils_Array::value('h', $date) != NULL ||
104 CRM_Utils_Array::value('i', $date) != NULL ||
105 CRM_Utils_Array::value('s', $date) != NULL
106 ) {
107 // we have time too..
108 if (!empty($date['h'])) {
109 if (CRM_Utils_Array::value('A', $date) == 'PM' or CRM_Utils_Array::value('a', $date) == 'pm') {
110 if ($date['h'] != 12) {
111 $date['h'] = $date['h'] + 12;
112 }
113 }
114 if ((CRM_Utils_Array::value('A', $date) == 'AM' or CRM_Utils_Array::value('a', $date) == 'am') &&
115 CRM_Utils_Array::value('h', $date) == 12
116 ) {
117 $date['h'] = '00';
118 }
119
120 $date['h'] = (int ) $date['h'];
121 }
122 else {
123 $date['h'] = 0;
124 }
125
126 // in 24-hour format the hour is under the 'H' key
127 if (!empty($date['H'])) {
128 $date['H'] = (int) $date['H'];
129 }
130 else {
131 $date['H'] = 0;
132 }
133
134 if (!empty($date['i'])) {
135 $date['i'] = (int ) $date['i'];
136 }
137 else {
138 $date['i'] = 0;
139 }
140
141 if ($date['h'] == 0 && $date['H'] != 0) {
142 $date['h'] = $date['H'];
143 }
144
145 if (!empty($date['s'])) {
146 $date['s'] = (int ) $date['s'];
147 }
148 else {
149 $date['s'] = 0;
150 }
151
152 $date['h'] = sprintf('%02d', $date['h']);
153 $date['i'] = sprintf('%02d', $date['i']);
154 $date['s'] = sprintf('%02d', $date['s']);
155
156 if ($separator) {
157 $time = '&nbsp;';
158 }
159 $time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
160 }
161
162 return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
163 }
164
165 /**
166 * Return abbreviated weekday names according to the locale.
167 *
168 * Array will be in localized order according to 'weekBegins' setting,
169 * but array keys will always match to:
170 * 0 => Sun
171 * 1 => Mon
172 * etc.
173 *
174 * @return array
175 * 0-based array with abbreviated weekday names
176 *
177 */
178 public static function getAbbrWeekdayNames() {
179 static $days = [];
180 if (!$days) {
181 // First day of the week
182 $firstDay = Civi::settings()->get('weekBegins');
183
184 // set LC_TIME and build the arrays from locale-provided names
185 // June 1st, 1970 was a Monday
186 CRM_Core_I18n::setLcTime();
187 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ? 0 : $i + 1) {
188 $days[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
189 }
190 }
191 return $days;
192 }
193
194 /**
195 * Return full weekday names according to the locale.
196 *
197 * Array will be in localized order according to 'weekBegins' setting,
198 * but array keys will always match to:
199 * 0 => Sunday
200 * 1 => Monday
201 * etc.
202 *
203 * @return array
204 * 0-based array with full weekday names
205 *
206 */
207 public static function getFullWeekdayNames() {
208 static $days = [];
209 if (!$days) {
210 // First day of the week
211 $firstDay = Civi::settings()->get('weekBegins');
212
213 // set LC_TIME and build the arrays from locale-provided names
214 // June 1st, 1970 was a Monday
215 CRM_Core_I18n::setLcTime();
216 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ? 0 : $i + 1) {
217 $days[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
218 }
219 }
220 return $days;
221 }
222
223 /**
224 * Return abbreviated month names according to the locale.
225 *
226 * @param bool $month
227 *
228 * @return array
229 * 1-based array with abbreviated month names
230 *
231 */
232 public static function &getAbbrMonthNames($month = FALSE) {
233 static $abbrMonthNames;
234 if (!isset($abbrMonthNames)) {
235
236 // set LC_TIME and build the arrays from locale-provided names
237 CRM_Core_I18n::setLcTime();
238 for ($i = 1; $i <= 12; $i++) {
239 $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
240 }
241 }
242 if ($month) {
243 return $abbrMonthNames[$month];
244 }
245 return $abbrMonthNames;
246 }
247
248 /**
249 * Return full month names according to the locale.
250 *
251 * @return array
252 * 1-based array with full month names
253 *
254 */
255 public static function &getFullMonthNames() {
256 static $fullMonthNames;
257 if (!isset($fullMonthNames)) {
258
259 // set LC_TIME and build the arrays from locale-provided names
260 CRM_Core_I18n::setLcTime();
261 for ($i = 1; $i <= 12; $i++) {
262 $fullMonthNames[$i] = strftime('%B', mktime(0, 0, 0, $i, 10, 1970));
263 }
264 }
265 return $fullMonthNames;
266 }
267
268 /**
269 * @param $string
270 *
271 * @return int
272 */
273 public static function unixTime($string) {
274 if (empty($string)) {
275 return 0;
276 }
277 $parsedDate = date_parse($string);
278 return mktime(CRM_Utils_Array::value('hour', $parsedDate),
279 CRM_Utils_Array::value('minute', $parsedDate),
280 59,
281 CRM_Utils_Array::value('month', $parsedDate),
282 CRM_Utils_Array::value('day', $parsedDate),
283 CRM_Utils_Array::value('year', $parsedDate)
284 );
285 }
286
287 /**
288 * Create a date and time string in a provided format.
289 *
290 * %b - abbreviated month name ('Jan'..'Dec')
291 * %B - full month name ('January'..'December')
292 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
293 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
294 * %E - day of the month as a decimal number ('1'..'31')
295 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
296 * %H - hour in 24-hour format, 0-padded ('00'..'23')
297 * %I - hour in 12-hour format, 0-padded ('01'..'12')
298 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
299 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
300 * %m - month as a decimal number, 0-padded ('01'..'12')
301 * %M - minute, 0-padded ('00'..'60')
302 * %p - lowercase ante/post meridiem ('am', 'pm')
303 * %P - uppercase ante/post meridiem ('AM', 'PM')
304 * %Y - year as a decimal number including the century ('2005')
305 *
306 * @param string $dateString
307 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
308 * @param string $format
309 * The output format.
310 * @param array $dateParts
311 * An array with the desired date parts.
312 *
313 * @return string
314 * the $format-formatted $date
315 */
316 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
317 // 1-based (January) month names arrays
318 $abbrMonths = self::getAbbrMonthNames();
319 $fullMonths = self::getFullMonthNames();
320
321 if (!$format) {
322 $config = CRM_Core_Config::singleton();
323
324 if ($dateParts) {
325 if (array_intersect(['h', 'H'], $dateParts)) {
326 $format = $config->dateformatDatetime;
327 }
328 elseif (array_intersect(['d', 'j'], $dateParts)) {
329 $format = $config->dateformatFull;
330 }
331 elseif (array_intersect(['m', 'M'], $dateParts)) {
332 $format = $config->dateformatPartial;
333 }
334 else {
335 $format = $config->dateformatYear;
336 }
337 }
338 else {
339 if (strpos($dateString, '-')) {
340 $month = (int) substr($dateString, 5, 2);
341 $day = (int) substr($dateString, 8, 2);
342 }
343 else {
344 $month = (int) substr($dateString, 4, 2);
345 $day = (int) substr($dateString, 6, 2);
346 }
347
348 if (strlen($dateString) > 10) {
349 $format = $config->dateformatDatetime;
350 }
351 elseif ($day > 0) {
352 $format = $config->dateformatFull;
353 }
354 elseif ($month > 0) {
355 $format = $config->dateformatPartial;
356 }
357 else {
358 $format = $config->dateformatYear;
359 }
360 }
361 }
362
363 if (!CRM_Utils_System::isNull($dateString)) {
364 if (strpos($dateString, '-')) {
365 $year = (int) substr($dateString, 0, 4);
366 $month = (int) substr($dateString, 5, 2);
367 $day = (int) substr($dateString, 8, 2);
368
369 $hour24 = (int) substr($dateString, 11, 2);
370 $minute = (int) substr($dateString, 14, 2);
371 }
372 else {
373 $year = (int) substr($dateString, 0, 4);
374 $month = (int) substr($dateString, 4, 2);
375 $day = (int) substr($dateString, 6, 2);
376
377 $hour24 = (int) substr($dateString, 8, 2);
378 $minute = (int) substr($dateString, 10, 2);
379 }
380
381 if ($day % 10 == 1 and $day != 11) {
382 $suffix = 'st';
383 }
384 elseif ($day % 10 == 2 and $day != 12) {
385 $suffix = 'nd';
386 }
387 elseif ($day % 10 == 3 and $day != 13) {
388 $suffix = 'rd';
389 }
390 else {
391 $suffix = 'th';
392 }
393
394 if ($hour24 < 12) {
395 if ($hour24 == 00) {
396 $hour12 = 12;
397 }
398 else {
399 $hour12 = $hour24;
400 }
401 $type = 'AM';
402 }
403 else {
404 if ($hour24 == 12) {
405 $hour12 = 12;
406 }
407 else {
408 $hour12 = $hour24 - 12;
409 }
410 $type = 'PM';
411 }
412
413 $date = [
414 '%b' => CRM_Utils_Array::value($month, $abbrMonths),
415 '%B' => CRM_Utils_Array::value($month, $fullMonths),
416 '%d' => $day > 9 ? $day : '0' . $day,
417 '%e' => $day > 9 ? $day : ' ' . $day,
418 '%E' => $day,
419 '%f' => $suffix,
420 '%H' => $hour24 > 9 ? $hour24 : '0' . $hour24,
421 '%h' => $hour12 > 9 ? $hour12 : '0' . $hour12,
422 '%I' => $hour12 > 9 ? $hour12 : '0' . $hour12,
423 '%k' => $hour24 > 9 ? $hour24 : ' ' . $hour24,
424 '%l' => $hour12 > 9 ? $hour12 : ' ' . $hour12,
425 '%m' => $month > 9 ? $month : '0' . $month,
426 '%M' => $minute > 9 ? $minute : '0' . $minute,
427 '%i' => $minute > 9 ? $minute : '0' . $minute,
428 '%p' => strtolower($type),
429 '%P' => $type,
430 '%A' => $type,
431 '%Y' => $year,
432 ];
433
434 return strtr($format, $date);
435 }
436 else {
437 return '';
438 }
439 }
440
441 /**
442 * Wrapper for customFormat that takes a timestamp
443 *
444 * @param int $timestamp
445 * Date and time in timestamp format.
446 * @param string $format
447 * The output format.
448 * @param array $dateParts
449 * An array with the desired date parts.
450 *
451 * @return string
452 * the $format-formatted $date
453 */
454 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
455 return CRM_Utils_Date::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
456 }
457
458 /**
459 * Converts the date/datetime from MySQL format to ISO format
460 *
461 * @param string $mysql
462 * Date/datetime in MySQL format.
463 *
464 * @return string
465 * date/datetime in ISO format
466 */
467 public static function mysqlToIso($mysql) {
468 $year = substr($mysql, 0, 4);
469 $month = substr($mysql, 4, 2);
470 $day = substr($mysql, 6, 2);
471 $hour = substr($mysql, 8, 2);
472 $minute = substr($mysql, 10, 2);
473 $second = substr($mysql, 12, 2);
474
475 $iso = '';
476 if ($year) {
477 $iso .= "$year";
478 }
479 if ($month) {
480 $iso .= "-$month";
481 if ($day) {
482 $iso .= "-$day";
483 }
484 }
485
486 if ($hour) {
487 $iso .= " $hour";
488 if ($minute) {
489 $iso .= ":$minute";
490 if ($second) {
491 $iso .= ":$second";
492 }
493 }
494 }
495 return $iso;
496 }
497
498 /**
499 * Converts the date/datetime from ISO format to MySQL format
500 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
501 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
502 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
503 *
504 * @param string $iso
505 * Date/datetime in ISO format.
506 *
507 * @return string
508 * date/datetime in MySQL format
509 */
510 public static function isoToMysql($iso) {
511 $dropArray = ['-' => '', ':' => '', ' ' => ''];
512 return strtr($iso, $dropArray);
513 }
514
515 /**
516 * Converts the any given date to default date format.
517 *
518 * @param array $params
519 * Has given date-format.
520 * @param int $dateType
521 * Type of date.
522 * @param string $dateParam
523 * Index of params.
524 *
525 * @return bool
526 */
527 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
528 $now = getdate();
529 $cen = substr($now['year'], 0, 2);
530 $prevCen = $cen - 1;
531
532 $value = NULL;
533 if (!empty($params[$dateParam])) {
534 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
535 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
536 }
537
538 switch ($dateType) {
539 case 1:
540 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
541 return FALSE;
542 }
543 break;
544
545 case 2:
546 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
547 return FALSE;
548 }
549 break;
550
551 case 4:
552 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
553 return FALSE;
554 }
555 break;
556
557 case 8:
558 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
559 return FALSE;
560 }
561 break;
562
563 case 16:
564 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
565 return FALSE;
566 }
567 break;
568
569 case 32:
570 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
571 return FALSE;
572 }
573 break;
574 }
575
576 if ($dateType == 1) {
577 $formattedDate = explode("-", $value);
578 if (count($formattedDate) == 3) {
579 $year = (int) $formattedDate[0];
580 $month = (int) $formattedDate[1];
581 $day = (int) $formattedDate[2];
582 }
583 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
584 return TRUE;
585 }
586 else {
587 return FALSE;
588 }
589 }
590
591 if ($dateType == 2 || $dateType == 4) {
592 $formattedDate = explode("/", $value);
593 if (count($formattedDate) != 3) {
594 $formattedDate = explode("-", $value);
595 }
596 if (count($formattedDate) == 3) {
597 $year = (int) $formattedDate[2];
598 $month = (int) $formattedDate[0];
599 $day = (int) $formattedDate[1];
600 }
601 else {
602 return FALSE;
603 }
604 }
605 if ($dateType == 8) {
606 $dateArray = explode(' ', $value);
607 // ignore comma(,)
608 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
609
610 $monthInt = 0;
611 $fullMonths = self::getFullMonthNames();
612 foreach ($fullMonths as $key => $val) {
613 if (strtolower($dateArray[0]) == strtolower($val)) {
614 $monthInt = $key;
615 break;
616 }
617 }
618 if (!$monthInt) {
619 $abbrMonths = self::getAbbrMonthNames();
620 foreach ($abbrMonths as $key => $val) {
621 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
622 $monthInt = $key;
623 break;
624 }
625 }
626 }
627 $year = (int) $dateArray[2];
628 $day = (int) $dateArray[1];
629 $month = (int) $monthInt;
630 }
631 if ($dateType == 16) {
632 $dateArray = explode('-', $value);
633 if (count($dateArray) != 3) {
634 $dateArray = explode('/', $value);
635 }
636
637 if (count($dateArray) == 3) {
638 $monthInt = 0;
639 $fullMonths = self::getFullMonthNames();
640 foreach ($fullMonths as $key => $val) {
641 if (strtolower($dateArray[1]) == strtolower($val)) {
642 $monthInt = $key;
643 break;
644 }
645 }
646 if (!$monthInt) {
647 $abbrMonths = self::getAbbrMonthNames();
648 foreach ($abbrMonths as $key => $val) {
649 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
650 $monthInt = $key;
651 break;
652 }
653 }
654 }
655 if (!$monthInt) {
656 $monthInt = $dateArray[1];
657 }
658
659 $year = (int) $dateArray[2];
660 $day = (int) $dateArray[0];
661 $month = (int) $monthInt;
662 }
663 else {
664 return FALSE;
665 }
666 }
667 if ($dateType == 32) {
668 $formattedDate = explode("/", $value);
669 if (count($formattedDate) == 3) {
670 $year = (int) $formattedDate[2];
671 $month = (int) $formattedDate[1];
672 $day = (int) $formattedDate[0];
673 }
674 else {
675 return FALSE;
676 }
677 }
678
679 $month = ($month < 10) ? "0" . "$month" : $month;
680 $day = ($day < 10) ? "0" . "$day" : $day;
681
682 $year = (int ) $year;
683 // simple heuristic to determine what century to use
684 // 00 - 20 is always 2000 - 2020
685 // 21 - 99 is always 1921 - 1999
686 if ($year < 21) {
687 $year = (strlen($year) == 1) ? $cen . '0' . $year : $cen . $year;
688 }
689 elseif ($year < 100) {
690 $year = $prevCen . $year;
691 }
692
693 if ($params[$dateParam]) {
694 $params[$dateParam] = "$year$month$day";
695 }
696 // if month is invalid return as error
697 if ($month !== '00' && $month <= 12) {
698 return TRUE;
699 }
700 return FALSE;
701 }
702
703 /**
704 * @param $date
705 *
706 * @return bool
707 */
708 public static function isDate(&$date) {
709 if (CRM_Utils_System::isNull($date)) {
710 return FALSE;
711 }
712 return TRUE;
713 }
714
715 /**
716 * Translate a TTL to a concrete expiration time.
717 *
718 * @param NULL|int|DateInterval $ttl
719 * @param int $default
720 * The value to use if $ttl is not specified (NULL).
721 * @return int
722 * Timestamp (seconds since epoch).
723 * @throws \CRM_Utils_Cache_InvalidArgumentException
724 */
725 public static function convertCacheTtlToExpires($ttl, $default) {
726 if ($ttl === NULL) {
727 $ttl = $default;
728 }
729
730 if (is_int($ttl)) {
731 return time() + $ttl;
732 }
733 elseif ($ttl instanceof DateInterval) {
734 return date_add(new DateTime(), $ttl)->getTimestamp();
735 }
736 else {
737 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
738 }
739 }
740
741 /**
742 * Normalize a TTL.
743 *
744 * @param NULL|int|DateInterval $ttl
745 * @param int $default
746 * The value to use if $ttl is not specified (NULL).
747 * @return int
748 * Seconds until expiration.
749 * @throws \CRM_Utils_Cache_InvalidArgumentException
750 */
751 public static function convertCacheTtl($ttl, $default) {
752 if ($ttl === NULL) {
753 return $default;
754 }
755 elseif (is_int($ttl)) {
756 return $ttl;
757 }
758 elseif ($ttl instanceof DateInterval) {
759 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
760 }
761 else {
762 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
763 }
764 }
765
766 /**
767 * @param null $timeStamp
768 *
769 * @return bool|string
770 */
771 public static function currentDBDate($timeStamp = NULL) {
772 return $timeStamp ? date('YmdHis', $timeStamp) : date('YmdHis');
773 }
774
775 /**
776 * @param $date
777 * @param null $now
778 *
779 * @return bool
780 */
781 public static function overdue($date, $now = NULL) {
782 $mysqlDate = self::isoToMysql($date);
783 if (!$now) {
784 $now = self::currentDBDate();
785 }
786 else {
787 $now = self::isoToMysql($now);
788 }
789
790 return (strtotime($mysqlDate) >= strtotime($now)) ? FALSE : TRUE;
791 }
792
793 /**
794 * Get customized today.
795 *
796 * This function is used for getting customized today. To get
797 * actuall today pass 'dayParams' as null. or else pass the day,
798 * month, year values as array values
799 * Example: $dayParams = array(
800 * 'day' => '25', 'month' => '10',
801 * 'year' => '2007' );
802 *
803 * @param array $dayParams of the day, month, year.
804 * Array of the day, month, year.
805 * values.
806 * @param string $format
807 * Expected date format( default.
808 * format is 2007-12-21 )
809 *
810 * @return string
811 * Return the customized today's date (Y-m-d)
812 */
813 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
814 if (is_null($dayParams) || empty($dayParams)) {
815 $today = date($format);
816 }
817 else {
818 $today = date($format, mktime(0, 0, 0,
819 $dayParams['month'],
820 $dayParams['day'],
821 $dayParams['year']
822 ));
823 }
824
825 return $today;
826 }
827
828 /**
829 * Find whether today's date lies in
830 * the given range
831 *
832 * @param date $startDate
833 * Start date for the range.
834 * @param date $endDate
835 * End date for the range.
836 *
837 * @return bool
838 * true if today's date is in the given date range
839 */
840 public static function getRange($startDate, $endDate) {
841 $today = date("Y-m-d");
842 $mysqlStartDate = self::isoToMysql($startDate);
843 $mysqlEndDate = self::isoToMysql($endDate);
844 $mysqlToday = self::isoToMysql($today);
845
846 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
847 return TRUE;
848 }
849 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
850 return TRUE;
851 }
852 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
853 return TRUE;
854 }
855 return FALSE;
856 }
857
858 /**
859 * Get start date and end from
860 * the given relative term and unit
861 *
862 * @param string $relative Relative format in the format term.unit.
863 * Eg: previous.day
864 *
865 * @param string $from
866 * @param string $to
867 * @param string $fromTime
868 * @param string $toTime
869 *
870 * @return array
871 * start date, end date
872 */
873 public static function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = '235959') {
874 if ($relative) {
875 list($term, $unit) = explode('.', $relative, 2);
876 $dateRange = self::relativeToAbsolute($term, $unit);
877 $from = substr($dateRange['from'], 0, 8);
878 $to = substr($dateRange['to'], 0, 8);
879 // @todo fix relativeToAbsolute & add tests
880 // relativeToAbsolute returns 8 char date strings
881 // or 14 char date + time strings.
882 // We should use those. However, it turns out to be unreliable.
883 // e.g. this.week does NOT return 235959 for 'from'
884 // so our defaults are more reliable.
885 // Currently relativeToAbsolute only supports 'whole' days so that is ok
886 }
887
888 $from = self::processDate($from, $fromTime);
889 $to = self::processDate($to, $toTime);
890
891 return [$from, $to];
892 }
893
894 /**
895 * Calculate Age in Years if greater than one year else in months.
896 *
897 * @param date $birthDate
898 * Birth Date.
899 *
900 * @return int
901 * array $results contains years or months
902 */
903 public static function calculateAge($birthDate) {
904 $results = [];
905 $formatedBirthDate = CRM_Utils_Date::customFormat($birthDate, '%Y-%m-%d');
906
907 $bDate = explode('-', $formatedBirthDate);
908 $birthYear = $bDate[0];
909 $birthMonth = $bDate[1];
910 $birthDay = $bDate[2];
911 $year_diff = date("Y") - $birthYear;
912
913 // don't calculate age CRM-3143
914 if ($birthYear == '1902') {
915 return $results;
916 }
917
918 switch ($year_diff) {
919 case 1:
920 $month = (12 - $birthMonth) + date("m");
921 if ($month < 12) {
922 if (date("d") < $birthDay) {
923 $month--;
924 }
925 $results['months'] = $month;
926 }
927 elseif ($month == 12 && (date("d") < $birthDay)) {
928 $results['months'] = $month - 1;
929 }
930 else {
931 $results['years'] = $year_diff;
932 }
933 break;
934
935 case 0:
936 $month = date("m") - $birthMonth;
937 $results['months'] = $month;
938 break;
939
940 default:
941 $results['years'] = $year_diff;
942 if ((date("m") < $birthMonth) || (date("m") == $birthMonth) && (date("d") < $birthDay)) {
943 $results['years']--;
944 }
945 }
946
947 return $results;
948 }
949
950 /**
951 * Calculate next payment date according to provided unit & interval
952 *
953 * @param string $unit
954 * Frequency unit like year,month, week etc.
955 *
956 * @param int $interval
957 * Frequency interval.
958 *
959 * @param array $date
960 * Start date of pledge.
961 *
962 * @param bool $dontCareTime
963 *
964 * @return array
965 * contains new date with added interval
966 */
967 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
968 if (is_array($date)) {
969 $hour = CRM_Utils_Array::value('H', $date);
970 $minute = CRM_Utils_Array::value('i', $date);
971 $second = CRM_Utils_Array::value('s', $date);
972 $month = CRM_Utils_Array::value('M', $date);
973 $day = CRM_Utils_Array::value('d', $date);
974 $year = CRM_Utils_Array::value('Y', $date);
975 }
976 else {
977 extract(date_parse($date));
978 }
979 $date = mktime($hour, $minute, $second, $month, $day, $year);
980 switch ($unit) {
981 case 'year':
982 $date = mktime($hour, $minute, $second, $month, $day, $year + $interval);
983 break;
984
985 case 'month':
986 $date = mktime($hour, $minute, $second, $month + $interval, $day, $year);
987 break;
988
989 case 'week':
990 $interval = $interval * 7;
991 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
992 break;
993
994 case 'day':
995 $date = mktime($hour, $minute, $second, $month, $day + $interval, $year);
996 break;
997
998 case 'second':
999 $date = mktime($hour, $minute, $second + $interval, $month, $day, $year);
1000 break;
1001 }
1002
1003 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1004
1005 $date = [];
1006 $date['M'] = $scheduleDate[0];
1007 $date['d'] = $scheduleDate[1];
1008 $date['Y'] = $scheduleDate[2];
1009 if ($dontCareTime == FALSE) {
1010 $date['H'] = $scheduleDate[3];
1011 $date['i'] = $scheduleDate[4];
1012 $date['s'] = $scheduleDate[5];
1013 }
1014 return $date;
1015 }
1016
1017 /**
1018 * Get the smarty view presentation mapping for the given format.
1019 *
1020 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1021 * they should be rendered using a longer date format. This is likely as much to
1022 * do with the earlier date widget being unable to handle some formats as usablity.
1023 * However, we continue to respect this.
1024 *
1025 * @param $format
1026 * Given format ( eg 'M Y', 'Y M' ).
1027 *
1028 * @return string|null
1029 * Smarty translation of the date format. Null is also valid and is translated
1030 * according to the available parts at the smarty layer.
1031 */
1032 public static function getDateFieldViewFormat($format) {
1033 $supportableFormats = [
1034 'mm/dd' => '%B %E%f',
1035 'dd-mm' => '%E%f %B',
1036 'yy-mm' => '%Y %B',
1037 'M yy' => '%b %Y',
1038 'yy' => '%Y',
1039 'dd/mm/yy' => '%E%f %B %Y',
1040 ];
1041
1042 return array_key_exists($format, $supportableFormats) ? $supportableFormats[$format] : self::pickBestSmartyFormat($format);
1043 }
1044
1045 /**
1046 * Pick the smarty format from settings that best matches the time string we have.
1047 *
1048 * For view purposes we historically use the setting that most closely matches the data
1049 * in the format from our settings, as opposed to the setting configured for the field.
1050 *
1051 * @param $format
1052 * @return mixed
1053 */
1054 public static function pickBestSmartyFormat($format) {
1055 if (stristr($format, 'h')) {
1056 return Civi::settings()->get('dateformatDatetime');
1057 }
1058 if (stristr($format, 'd') || stristr($format, 'j')) {
1059 return Civi::settings()->get('dateformatFull');
1060 }
1061 if (stristr($format, 'm')) {
1062 return Civi::settings()->get('dateformatPartial');
1063 }
1064 return Civi::settings()->get('dateformatYear');
1065 }
1066
1067 /**
1068 * Map date plugin and actual format that is used by PHP.
1069 *
1070 * @return array
1071 */
1072 public static function datePluginToPHPFormats() {
1073 $dateInputFormats = [
1074 "mm/dd/yy" => 'm/d/Y',
1075 "dd/mm/yy" => 'd/m/Y',
1076 "yy-mm-dd" => 'Y-m-d',
1077 "dd-mm-yy" => 'd-m-Y',
1078 "dd.mm.yy" => 'd.m.Y',
1079 "M d" => 'M j',
1080 "M d, yy" => 'M j, Y',
1081 "d M yy" => 'j M Y',
1082 "MM d, yy" => 'F j, Y',
1083 "d MM yy" => 'j F Y',
1084 "DD, d MM yy" => 'l, j F Y',
1085 "mm/dd" => 'm/d',
1086 "dd-mm" => 'd-m',
1087 "yy-mm" => 'Y-m',
1088 "M yy" => 'M Y',
1089 "M Y" => 'M Y',
1090 "yy" => 'Y',
1091 ];
1092 return $dateInputFormats;
1093 }
1094
1095 /**
1096 * Resolves the given relative time interval into finite time limits.
1097 *
1098 * @param string $relativeTerm
1099 * Relative time frame: this, previous, previous_1.
1100 * @param int $unit
1101 * Frequency unit like year, month, week etc.
1102 *
1103 * @return array
1104 * start date and end date for the relative time frame
1105 */
1106 public static function relativeToAbsolute($relativeTerm, $unit) {
1107 $now = getdate();
1108 $from = $to = $dateRange = [];
1109 $from['H'] = $from['i'] = $from['s'] = 0;
1110 $relativeTermParts = explode('_', $relativeTerm);
1111 $relativeTermPrefix = $relativeTermParts[0];
1112 $relativeTermSuffix = isset($relativeTermParts[1]) ? $relativeTermParts[1] : '';
1113
1114 switch ($unit) {
1115 case 'year':
1116 switch ($relativeTerm) {
1117 case 'previous':
1118 $from['M'] = $from['d'] = 1;
1119 $to['d'] = 31;
1120 $to['M'] = 12;
1121 $to['Y'] = $from['Y'] = $now['year'] - 1;
1122 break;
1123
1124 case 'previous_before':
1125 $from['M'] = $from['d'] = 1;
1126 $to['d'] = 31;
1127 $to['M'] = 12;
1128 $to['Y'] = $from['Y'] = $now['year'] - 2;
1129 break;
1130
1131 case 'previous_2':
1132 $from['M'] = $from['d'] = 1;
1133 $to['d'] = 31;
1134 $to['M'] = 12;
1135 $from['Y'] = $now['year'] - 2;
1136 $to['Y'] = $now['year'] - 1;
1137 break;
1138
1139 case 'earlier':
1140 $to['d'] = 31;
1141 $to['M'] = 12;
1142 $to['Y'] = $now['year'] - 1;
1143 unset($from);
1144 break;
1145
1146 case 'greater':
1147 $from['M'] = $from['d'] = 1;
1148 $from['Y'] = $now['year'];
1149 unset($to);
1150 break;
1151
1152 case 'greater_previous':
1153 $from['d'] = 31;
1154 $from['M'] = 12;
1155 $from['Y'] = $now['year'] - 1;
1156 unset($to);
1157 break;
1158
1159 case 'ending':
1160 $to['d'] = $now['mday'];
1161 $to['M'] = $now['mon'];
1162 $to['Y'] = $now['year'];
1163 $to['H'] = 23;
1164 $to['i'] = $to['s'] = 59;
1165 $from = self::intervalAdd('year', -1, $to);
1166 $from = self::intervalAdd('second', 1, $from);
1167 break;
1168
1169 case 'current':
1170 $from['M'] = $from['d'] = 1;
1171 $from['Y'] = $now['year'];
1172 $to['H'] = 23;
1173 $to['i'] = $to['s'] = 59;
1174 $to['d'] = $now['mday'];
1175 $to['M'] = $now['mon'];
1176 $to['Y'] = $now['year'];
1177 break;
1178
1179 case 'ending_2':
1180 $to['d'] = $now['mday'];
1181 $to['M'] = $now['mon'];
1182 $to['Y'] = $now['year'];
1183 $to['H'] = 23;
1184 $to['i'] = $to['s'] = 59;
1185 $from = self::intervalAdd('year', -2, $to);
1186 $from = self::intervalAdd('second', 1, $from);
1187 break;
1188
1189 case 'ending_3':
1190 $to['d'] = $now['mday'];
1191 $to['M'] = $now['mon'];
1192 $to['Y'] = $now['year'];
1193 $to['H'] = 23;
1194 $to['i'] = $to['s'] = 59;
1195 $from = self::intervalAdd('year', -3, $to);
1196 $from = self::intervalAdd('second', 1, $from);
1197 break;
1198
1199 case 'less':
1200 $to['d'] = 31;
1201 $to['M'] = 12;
1202 $to['Y'] = $now['year'];
1203 unset($from);
1204 break;
1205
1206 case 'next':
1207 $from['M'] = $from['d'] = 1;
1208 $to['d'] = 31;
1209 $to['M'] = 12;
1210 $to['Y'] = $from['Y'] = $now['year'] + 1;
1211 break;
1212
1213 case 'starting':
1214 $from['d'] = $now['mday'];
1215 $from['M'] = $now['mon'];
1216 $from['Y'] = $now['year'];
1217 $to['d'] = $now['mday'] - 1;
1218 $to['M'] = $now['mon'];
1219 $to['Y'] = $now['year'] + 1;
1220 break;
1221
1222 default:
1223 switch ($relativeTermPrefix) {
1224
1225 case 'ending':
1226 $to['d'] = $now['mday'];
1227 $to['M'] = $now['mon'];
1228 $to['Y'] = $now['year'];
1229 $to['H'] = 23;
1230 $to['i'] = $to['s'] = 59;
1231 $from = self::intervalAdd('year', -$relativeTermSuffix, $to);
1232 $from = self::intervalAdd('second', 1, $from);
1233 break;
1234
1235 case 'this':
1236 $from['d'] = $from['M'] = 1;
1237 $to['d'] = 31;
1238 $to['M'] = 12;
1239 $to['Y'] = $from['Y'] = $now['year'];
1240 if (is_numeric($relativeTermSuffix)) {
1241 $from['Y'] -= ($relativeTermSuffix - 1);
1242 }
1243 break;
1244 }
1245 break;
1246 }
1247 break;
1248
1249 case 'fiscal_year':
1250 $config = CRM_Core_Config::singleton();
1251 $from['d'] = $config->fiscalYearStart['d'];
1252 $from['M'] = $config->fiscalYearStart['M'];
1253 $fYear = self::calculateFiscalYear($from['d'], $from['M']);
1254 switch ($relativeTermPrefix) {
1255 case 'this':
1256 $from['Y'] = $fYear;
1257 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1258 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1259 $to['d'] = $fiscalEnd['2'];
1260 $to['M'] = $fiscalEnd['1'];
1261 $to['Y'] = $fiscalEnd['0'];
1262 $to['H'] = 23;
1263 $to['i'] = $to['s'] = 59;
1264 if (is_numeric($relativeTermSuffix)) {
1265 $from = self::intervalAdd('year', (-$relativeTermSuffix), $to);
1266 $from = self::intervalAdd('second', 1, $from);
1267 }
1268 break;
1269
1270 case 'previous':
1271 if (!is_numeric($relativeTermSuffix)) {
1272 $from['Y'] = ($relativeTermSuffix === 'before') ? $fYear - 2 : $fYear - 1;
1273 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1274 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1275 $to['d'] = $fiscalEnd['2'];
1276 $to['M'] = $fiscalEnd['1'];
1277 $to['Y'] = $fiscalEnd['0'];
1278 $to['H'] = 23;
1279 $to['i'] = $to['s'] = 59;
1280 }
1281 else {
1282 $from['Y'] = $fYear - $relativeTermSuffix;
1283 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1284 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1285 $to['d'] = $fiscalEnd['2'];
1286 $to['M'] = $fiscalEnd['1'];
1287 $to['Y'] = $fYear;
1288 $to['H'] = 23;
1289 $to['i'] = $to['s'] = 59;
1290 }
1291 break;
1292
1293 case 'next':
1294 $from['Y'] = $fYear + 1;
1295 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] + 1);
1296 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1297 $to['d'] = $fiscalEnd['2'];
1298 $to['M'] = $fiscalEnd['1'];
1299 $to['Y'] = $fiscalEnd['0'];
1300 break;
1301 }
1302 break;
1303
1304 case 'quarter':
1305 switch ($relativeTerm) {
1306 case 'this':
1307
1308 $quarter = ceil($now['mon'] / 3);
1309 $from['d'] = 1;
1310 $from['M'] = (3 * $quarter) - 2;
1311 $to['M'] = 3 * $quarter;
1312 $to['Y'] = $from['Y'] = $now['year'];
1313 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1314 break;
1315
1316 case 'previous':
1317 $difference = 1;
1318 $quarter = ceil($now['mon'] / 3);
1319 $quarter = $quarter - $difference;
1320 $subtractYear = 0;
1321 if ($quarter <= 0) {
1322 $subtractYear = 1;
1323 $quarter += 4;
1324 }
1325 $from['d'] = 1;
1326 $from['M'] = (3 * $quarter) - 2;
1327 $to['M'] = 3 * $quarter;
1328 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1329 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1330 break;
1331
1332 case 'previous_before':
1333 $difference = 2;
1334 $quarter = ceil($now['mon'] / 3);
1335 $quarter = $quarter - $difference;
1336 $subtractYear = 0;
1337 if ($quarter <= 0) {
1338 $subtractYear = 1;
1339 $quarter += 4;
1340 }
1341 $from['d'] = 1;
1342 $from['M'] = (3 * $quarter) - 2;
1343 $to['M'] = 3 * $quarter;
1344 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1345 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1346 break;
1347
1348 case 'previous_2':
1349 $difference = 2;
1350 $quarter = ceil($now['mon'] / 3);
1351 $current_quarter = $quarter;
1352 $quarter = $quarter - $difference;
1353 $subtractYear = 0;
1354 if ($quarter <= 0) {
1355 $subtractYear = 1;
1356 $quarter += 4;
1357 }
1358 $from['d'] = 1;
1359 $from['M'] = (3 * $quarter) - 2;
1360 switch ($current_quarter) {
1361 case 1:
1362 $to['M'] = (4 * $quarter);
1363 break;
1364
1365 case 2:
1366 $to['M'] = (4 * $quarter) + 3;
1367 break;
1368
1369 case 3:
1370 $to['M'] = (4 * $quarter) + 2;
1371 break;
1372
1373 case 4:
1374 $to['M'] = (4 * $quarter) + 1;
1375 break;
1376 }
1377 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1378 if ($to['M'] > 12) {
1379 $to['M'] = 3 * ($quarter - 3);
1380 $to['Y'] = $now['year'];
1381 }
1382 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1383 break;
1384
1385 case 'earlier':
1386 $quarter = ceil($now['mon'] / 3) - 1;
1387 $subtractYear = 0;
1388 if ($quarter <= 0) {
1389 $subtractYear = 1;
1390 $quarter += 4;
1391 }
1392 $to['M'] = 3 * $quarter;
1393 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1394 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1395 unset($from);
1396 break;
1397
1398 case 'greater':
1399 $quarter = ceil($now['mon'] / 3);
1400 $from['d'] = 1;
1401 $from['M'] = (3 * $quarter) - 2;
1402 $from['Y'] = $now['year'];
1403 unset($to);
1404 break;
1405
1406 case 'greater_previous':
1407 $quarter = ceil($now['mon'] / 3) - 1;
1408 $subtractYear = 0;
1409 if ($quarter <= 0) {
1410 $subtractYear = 1;
1411 $quarter += 4;
1412 }
1413 $from['M'] = 3 * $quarter;
1414 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1415 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1416 unset($to);
1417 break;
1418
1419 case 'ending':
1420 $to['d'] = $now['mday'];
1421 $to['M'] = $now['mon'];
1422 $to['Y'] = $now['year'];
1423 $to['H'] = 23;
1424 $to['i'] = $to['s'] = 59;
1425 $from = self::intervalAdd('day', -90, $to);
1426 $from = self::intervalAdd('second', 1, $from);
1427 break;
1428
1429 case 'current':
1430 $quarter = ceil($now['mon'] / 3);
1431 $from['d'] = 1;
1432 $from['M'] = (3 * $quarter) - 2;
1433 $from['Y'] = $now['year'];
1434 $to['d'] = $now['mday'];
1435 $to['M'] = $now['mon'];
1436 $to['Y'] = $now['year'];
1437 $to['H'] = 23;
1438 $to['i'] = $to['s'] = 59;
1439 break;
1440
1441 case 'less':
1442 $quarter = ceil($now['mon'] / 3);
1443 $to['M'] = 3 * $quarter;
1444 $to['Y'] = $now['year'];
1445 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1446 unset($from);
1447 break;
1448
1449 case 'next':
1450 $difference = -1;
1451 $subtractYear = 0;
1452 $quarter = ceil($now['mon'] / 3);
1453 $quarter = $quarter - $difference;
1454 // CRM-14550 QA Fix
1455 if ($quarter > 4) {
1456 $now['year'] = $now['year'] + 1;
1457 $quarter = 1;
1458 }
1459 if ($quarter <= 0) {
1460 $subtractYear = 1;
1461 $quarter += 4;
1462 }
1463 $from['d'] = 1;
1464 $from['M'] = (3 * $quarter) - 2;
1465 $to['M'] = 3 * $quarter;
1466 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1467 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1468 break;
1469
1470 case 'starting':
1471 $from['d'] = $now['mday'];
1472 $from['M'] = $now['mon'];
1473 $from['Y'] = $now['year'];
1474 $from['H'] = 00;
1475 $from['i'] = $to['s'] = 00;
1476 $to = self::intervalAdd('day', 90, $from);
1477 $to = self::intervalAdd('second', -1, $to);
1478 break;
1479
1480 default:
1481 if ($relativeTermPrefix === 'ending') {
1482 $to['d'] = $now['mday'];
1483 $to['M'] = $now['mon'];
1484 $to['Y'] = $now['year'];
1485 $to['H'] = 23;
1486 $to['i'] = $to['s'] = 59;
1487 $from = self::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1488 $from = self::intervalAdd('second', 1, $from);
1489 }
1490 }
1491 break;
1492
1493 case 'month':
1494 switch ($relativeTerm) {
1495 case 'this':
1496 $from['d'] = 1;
1497 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1498 $from['M'] = $to['M'] = $now['mon'];
1499 $from['Y'] = $to['Y'] = $now['year'];
1500 break;
1501
1502 case 'previous':
1503 $from['d'] = 1;
1504 if ($now['mon'] == 1) {
1505 $from['M'] = $to['M'] = 12;
1506 $from['Y'] = $to['Y'] = $now['year'] - 1;
1507 }
1508 else {
1509 $from['M'] = $to['M'] = $now['mon'] - 1;
1510 $from['Y'] = $to['Y'] = $now['year'];
1511 }
1512 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1513 break;
1514
1515 case 'previous_before':
1516 $from['d'] = 1;
1517 if ($now['mon'] < 3) {
1518 $from['M'] = $to['M'] = 10 + $now['mon'];
1519 $from['Y'] = $to['Y'] = $now['year'] - 1;
1520 }
1521 else {
1522 $from['M'] = $to['M'] = $now['mon'] - 2;
1523 $from['Y'] = $to['Y'] = $now['year'];
1524 }
1525 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1526 break;
1527
1528 case 'previous_2':
1529 $from['d'] = 1;
1530 if ($now['mon'] < 3) {
1531 $from['M'] = 10 + $now['mon'];
1532 $from['Y'] = $now['year'] - 1;
1533 }
1534 else {
1535 $from['M'] = $now['mon'] - 2;
1536 $from['Y'] = $now['year'];
1537 }
1538
1539 if ($now['mon'] == 1) {
1540 $to['M'] = 12;
1541 $to['Y'] = $now['year'] - 1;
1542 }
1543 else {
1544 $to['M'] = $now['mon'] - 1;
1545 $to['Y'] = $now['year'];
1546 }
1547
1548 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1549 break;
1550
1551 case 'earlier':
1552 // before end of past month
1553 if ($now['mon'] == 1) {
1554 $to['M'] = 12;
1555 $to['Y'] = $now['year'] - 1;
1556 }
1557 else {
1558 $to['M'] = $now['mon'] - 1;
1559 $to['Y'] = $now['year'];
1560 }
1561
1562 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1563 unset($from);
1564 break;
1565
1566 case 'greater':
1567 $from['d'] = 1;
1568 $from['M'] = $now['mon'];;
1569 $from['Y'] = $now['year'];
1570 unset($to);
1571 break;
1572
1573 case 'greater_previous':
1574 // from end of past month
1575 if ($now['mon'] == 1) {
1576 $from['M'] = 12;
1577 $from['Y'] = $now['year'] - 1;
1578 }
1579 else {
1580 $from['M'] = $now['mon'] - 1;
1581 $from['Y'] = $now['year'];
1582 }
1583
1584 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1585 unset($to);
1586 break;
1587
1588 case 'ending_2':
1589 $to['d'] = $now['mday'];
1590 $to['M'] = $now['mon'];
1591 $to['Y'] = $now['year'];
1592 $to['H'] = 23;
1593 $to['i'] = $to['s'] = 59;
1594 $from = self::intervalAdd('day', -60, $to);
1595 $from = self::intervalAdd('second', 1, $from);
1596 break;
1597
1598 case 'ending':
1599 $to['d'] = $now['mday'];
1600 $to['M'] = $now['mon'];
1601 $to['Y'] = $now['year'];
1602 $to['H'] = 23;
1603 $to['i'] = $to['s'] = 59;
1604 $from = self::intervalAdd('day', -30, $to);
1605 $from = self::intervalAdd('second', 1, $from);
1606 break;
1607
1608 case 'current':
1609 $from['d'] = 1;
1610 $from['M'] = $now['mon'];;
1611 $from['Y'] = $now['year'];
1612 $to['d'] = $now['mday'];
1613 $to['M'] = $now['mon'];
1614 $to['Y'] = $now['year'];
1615 $to['H'] = 23;
1616 $to['i'] = $to['s'] = 59;
1617 break;
1618
1619 case 'less':
1620 // CRM-14550 QA Fix
1621 $to['Y'] = $now['year'];
1622 $to['M'] = $now['mon'];
1623 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1624 unset($from);
1625 break;
1626
1627 case 'next':
1628 $from['d'] = 1;
1629 if ($now['mon'] == 12) {
1630 $from['M'] = $to['M'] = 1;
1631 $from['Y'] = $to['Y'] = $now['year'] + 1;
1632 }
1633 else {
1634 $from['M'] = $to['M'] = $now['mon'] + 1;
1635 $from['Y'] = $to['Y'] = $now['year'];
1636 }
1637 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1638 break;
1639
1640 case 'starting':
1641 $from['d'] = $now['mday'];
1642 $from['M'] = $now['mon'];
1643 $from['Y'] = $now['year'];
1644 $from['H'] = 00;
1645 $from['i'] = $to['s'] = 00;
1646 $to = self::intervalAdd('day', 30, $from);
1647 $to = self::intervalAdd('second', -1, $to);
1648 break;
1649
1650 case 'starting_2':
1651 $from['d'] = $now['mday'];
1652 $from['M'] = $now['mon'];
1653 $from['Y'] = $now['year'];
1654 $from['H'] = 00;
1655 $from['i'] = $to['s'] = 00;
1656 $to = self::intervalAdd('day', 60, $from);
1657 $to = self::intervalAdd('second', -1, $to);
1658 break;
1659
1660 default:
1661 if ($relativeTermPrefix === 'ending') {
1662 $to['d'] = $now['mday'];
1663 $to['M'] = $now['mon'];
1664 $to['Y'] = $now['year'];
1665 $to['H'] = 23;
1666 $to['i'] = $to['s'] = 59;
1667 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1668 $from = self::intervalAdd('second', 1, $from);
1669 }
1670 }
1671 break;
1672
1673 case 'week':
1674 $weekFirst = Civi::settings()->get('weekBegins');
1675 $thisDay = $now['wday'];
1676 if ($weekFirst > $thisDay) {
1677 $diffDay = $thisDay - $weekFirst + 7;
1678 }
1679 else {
1680 $diffDay = $thisDay - $weekFirst;
1681 }
1682 switch ($relativeTerm) {
1683 case 'this':
1684 $from['d'] = $now['mday'];
1685 $from['M'] = $now['mon'];
1686 $from['Y'] = $now['year'];
1687 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1688 $to = self::intervalAdd('day', 6, $from);
1689 break;
1690
1691 case 'previous':
1692 $from['d'] = $now['mday'];
1693 $from['M'] = $now['mon'];
1694 $from['Y'] = $now['year'];
1695 $from = self::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1696 $to = self::intervalAdd('day', 6, $from);
1697 break;
1698
1699 case 'previous_before':
1700 $from['d'] = $now['mday'];
1701 $from['M'] = $now['mon'];
1702 $from['Y'] = $now['year'];
1703 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1704 $to = self::intervalAdd('day', 6, $from);
1705 break;
1706
1707 case 'previous_2':
1708 $from['d'] = $now['mday'];
1709 $from['M'] = $now['mon'];
1710 $from['Y'] = $now['year'];
1711 $from = self::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1712 $to = self::intervalAdd('day', 13, $from);
1713 break;
1714
1715 case 'earlier':
1716 $to['d'] = $now['mday'];
1717 $to['M'] = $now['mon'];
1718 $to['Y'] = $now['year'];
1719 $to = self::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1720 unset($from);
1721 break;
1722
1723 case 'greater':
1724 $from['d'] = $now['mday'];
1725 $from['M'] = $now['mon'];
1726 $from['Y'] = $now['year'];
1727 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1728 unset($to);
1729 break;
1730
1731 case 'greater_previous':
1732 $from['d'] = $now['mday'];
1733 $from['M'] = $now['mon'];
1734 $from['Y'] = $now['year'];
1735 $from = self::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1736 unset($to);
1737 break;
1738
1739 case 'ending':
1740 $to['d'] = $now['mday'];
1741 $to['M'] = $now['mon'];
1742 $to['Y'] = $now['year'];
1743 $to['H'] = 23;
1744 $to['i'] = $to['s'] = 59;
1745 $from = self::intervalAdd('day', -7, $to);
1746 $from = self::intervalAdd('second', 1, $from);
1747 break;
1748
1749 case 'current':
1750 $from['d'] = $now['mday'];
1751 $from['M'] = $now['mon'];
1752 $from['Y'] = $now['year'];
1753 $from = self::intervalAdd('day', -1 * ($diffDay), $from);
1754 $to['d'] = $now['mday'];
1755 $to['M'] = $now['mon'];
1756 $to['Y'] = $now['year'];
1757 $to['H'] = 23;
1758 $to['i'] = $to['s'] = 59;
1759 break;
1760
1761 case 'less':
1762 $to['d'] = $now['mday'];
1763 $to['M'] = $now['mon'];
1764 $to['Y'] = $now['year'];
1765 // CRM-14550 QA Fix
1766 $to = self::intervalAdd('day', -1 * ($diffDay) + 6, $to);
1767 unset($from);
1768 break;
1769
1770 case 'next':
1771 $from['d'] = $now['mday'];
1772 $from['M'] = $now['mon'];
1773 $from['Y'] = $now['year'];
1774 $from = self::intervalAdd('day', -1 * ($diffDay) + 7, $from);
1775 $to = self::intervalAdd('day', 6, $from);
1776 break;
1777
1778 case 'starting':
1779 $from['d'] = $now['mday'];
1780 $from['M'] = $now['mon'];
1781 $from['Y'] = $now['year'];
1782 $from['H'] = 00;
1783 $from['i'] = $to['s'] = 00;
1784 $to = self::intervalAdd('day', 7, $from);
1785 $to = self::intervalAdd('second', -1, $to);
1786 break;
1787
1788 default:
1789 if ($relativeTermPrefix === 'ending') {
1790 $to['d'] = $now['mday'];
1791 $to['M'] = $now['mon'];
1792 $to['Y'] = $now['year'];
1793 $to['H'] = 23;
1794 $to['i'] = $to['s'] = 59;
1795 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1796 $from = self::intervalAdd('second', 1, $from);
1797 }
1798 }
1799 break;
1800
1801 case 'day':
1802 switch ($relativeTerm) {
1803 case 'this':
1804 $from['d'] = $to['d'] = $now['mday'];
1805 $from['M'] = $to['M'] = $now['mon'];
1806 $from['Y'] = $to['Y'] = $now['year'];
1807 break;
1808
1809 case 'previous':
1810 $from['d'] = $now['mday'];
1811 $from['M'] = $now['mon'];
1812 $from['Y'] = $now['year'];
1813 $from = self::intervalAdd('day', -1, $from);
1814 $to['d'] = $from['d'];
1815 $to['M'] = $from['M'];
1816 $to['Y'] = $from['Y'];
1817 break;
1818
1819 case 'previous_before':
1820 $from['d'] = $now['mday'];
1821 $from['M'] = $now['mon'];
1822 $from['Y'] = $now['year'];
1823 $from = self::intervalAdd('day', -2, $from);
1824 $to['d'] = $from['d'];
1825 $to['M'] = $from['M'];
1826 $to['Y'] = $from['Y'];
1827 break;
1828
1829 case 'previous_2':
1830 $from['d'] = $to['d'] = $now['mday'];
1831 $from['M'] = $to['M'] = $now['mon'];
1832 $from['Y'] = $to['Y'] = $now['year'];
1833 $from = self::intervalAdd('day', -2, $from);
1834 $to = self::intervalAdd('day', -1, $to);
1835 break;
1836
1837 case 'earlier':
1838 $to['d'] = $now['mday'];
1839 $to['M'] = $now['mon'];
1840 $to['Y'] = $now['year'];
1841 unset($from);
1842 break;
1843
1844 case 'greater':
1845 $from['d'] = $now['mday'];
1846 $from['M'] = $now['mon'];;
1847 $from['Y'] = $now['year'];
1848 unset($to);
1849 break;
1850
1851 case 'starting':
1852 $to['d'] = $now['mday'];
1853 $to['M'] = $now['mon'];
1854 $to['Y'] = $now['year'];
1855 $to = self::intervalAdd('day', 1, $to);
1856 $from['d'] = $to['d'];
1857 $from['M'] = $to['M'];
1858 $from['Y'] = $to['Y'];
1859 break;
1860
1861 default:
1862 if ($relativeTermPrefix === 'ending') {
1863 $to['d'] = $now['mday'];
1864 $to['M'] = $now['mon'];
1865 $to['Y'] = $now['year'];
1866 $to['H'] = 23;
1867 $to['i'] = $to['s'] = 59;
1868 $from = self::intervalAdd($unit, -$relativeTermSuffix, $to);
1869 $from = self::intervalAdd('second', 1, $from);
1870 }
1871 }
1872 break;
1873 }
1874
1875 $dateRange['from'] = empty($from) ? NULL : self::format($from);
1876 $dateRange['to'] = empty($to) ? NULL : self::format($to);
1877 return $dateRange;
1878 }
1879
1880 /**
1881 * Calculate current fiscal year based on the fiscal month and day.
1882 *
1883 * @param int $fyDate
1884 * Fiscal start date.
1885 *
1886 * @param int $fyMonth
1887 * Fiscal Start Month.
1888 *
1889 * @return int
1890 * $fy Current Fiscal Year
1891 */
1892 public static function calculateFiscalYear($fyDate, $fyMonth) {
1893 $date = date("Y-m-d");
1894 $currentYear = date("Y");
1895
1896 // recalculate the date because month 4::04 make the difference
1897 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1898 $fyDate = $fiscalYear[2];
1899 $fyMonth = $fiscalYear[1];
1900 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1901
1902 if ($fyStartDate > $date) {
1903 $fy = intval(intval($currentYear) - 1);
1904 }
1905 else {
1906 $fy = intval($currentYear);
1907 }
1908 return $fy;
1909 }
1910
1911 /**
1912 * Function to process date, convert to mysql format
1913 *
1914 * @param string $date
1915 * Date string.
1916 * @param string $time
1917 * Time string.
1918 * @param bool|string $returnNullString 'null' needs to be returned
1919 * so that db oject will set null in db
1920 * @param string $format
1921 * Expected return date format.( default is mysql ).
1922 *
1923 * @return string
1924 * date format that is excepted by mysql
1925 */
1926 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1927 $mysqlDate = NULL;
1928
1929 if ($returnNullString) {
1930 $mysqlDate = 'null';
1931 }
1932
1933 if (trim($date)) {
1934 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1935 }
1936
1937 return $mysqlDate;
1938 }
1939
1940 /**
1941 * Add the metadata about a date field to the field.
1942 *
1943 * This metadata will work with the call $form->add('datepicker', ...
1944 *
1945 * @param array $fieldMetaData
1946 * @param array $field
1947 *
1948 * @return array
1949 */
1950 public static function addDateMetadataToField($fieldMetaData, $field) {
1951 if (isset($fieldMetaData['html'])) {
1952 $field['html_type'] = $fieldMetaData['html']['type'];
1953 if ($field['html_type'] === 'Select Date') {
1954 if (!isset($field['date_format'])) {
1955 $dateAttributes = CRM_Core_SelectValues::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1956 $field['start_date_years'] = $dateAttributes['minYear'];
1957 $field['end_date_years'] = $dateAttributes['maxYear'];
1958 $field['date_format'] = $dateAttributes['format'];
1959 $field['is_datetime_field'] = TRUE;
1960 $field['time_format'] = $dateAttributes['time'];
1961 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1962 }
1963 $field['datepicker']['extra'] = self::getDatePickerExtra($field);
1964 $field['datepicker']['attributes'] = self::getDatePickerAttributes($field);
1965 }
1966 }
1967 return $field;
1968 }
1969
1970 /**
1971 * Get the fields required for the 'extra' parameter when adding a datepicker.
1972 *
1973 * @param array $field
1974 *
1975 * @return array
1976 */
1977 public static function getDatePickerExtra($field) {
1978 $extra = [];
1979 if (isset($field['date_format'])) {
1980 $extra['date'] = $field['date_format'];
1981 $extra['time'] = $field['time_format'];
1982 }
1983 $thisYear = date('Y');
1984 if (isset($field['start_date_years'])) {
1985 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1986 }
1987 if (isset($field['end_date_years'])) {
1988 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1989 }
1990 return $extra;
1991 }
1992
1993 /**
1994 * Get the attributes parameters required for datepicker.
1995 *
1996 * @param array $field
1997 * Field metadata
1998 *
1999 * @return array
2000 * Array ready to pass to $this->addForm('datepicker' as attributes.
2001 */
2002 public static function getDatePickerAttributes(&$field) {
2003 $attributes = [];
2004 $dateAttributes = [
2005 'start_date_years' => 'minYear',
2006 'end_date_years' => 'maxYear',
2007 'date_format' => 'format',
2008 ];
2009 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2010 if (isset($field[$dateAttribute])) {
2011 $attributes[$mapTo] = $field[$dateAttribute];
2012 }
2013 }
2014 return $attributes;
2015 }
2016
2017 /**
2018 * Function to convert mysql to date plugin format.
2019 *
2020 * @param string $mysqlDate
2021 * Date string.
2022 *
2023 * @param null $formatType
2024 * @param null $format
2025 * @param null $timeFormat
2026 *
2027 * @return array
2028 * and time
2029 */
2030 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2031 // if date is not passed assume it as today
2032 if (!$mysqlDate) {
2033 $mysqlDate = date('Y-m-d G:i:s');
2034 }
2035
2036 $config = CRM_Core_Config::singleton();
2037 if ($formatType) {
2038 // get actual format
2039 $params = ['name' => $formatType];
2040 $values = [];
2041 CRM_Core_DAO::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2042
2043 if ($values['date_format']) {
2044 $format = $values['date_format'];
2045 }
2046
2047 if (isset($values['time_format'])) {
2048 $timeFormat = $values['time_format'];
2049 }
2050 }
2051
2052 // now we set display date using js, hence we should always setdefault
2053 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
2054 // note that for date display we dynamically create text field
2055 /*
2056 if ( !$format ) {
2057 $format = $config->dateInputFormat;
2058 }
2059
2060 // get actual format
2061 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
2062 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
2063 */
2064
2065 $dateFormat = 'm/d/Y';
2066 $date = date($dateFormat, strtotime($mysqlDate));
2067
2068 if (!$timeFormat) {
2069 $timeFormat = $config->timeInputFormat;
2070 }
2071
2072 $actualTimeFormat = "g:iA";
2073 $appendZeroLength = 7;
2074 if ($timeFormat > 1) {
2075 $actualTimeFormat = "G:i";
2076 $appendZeroLength = 5;
2077 }
2078
2079 $time = date($actualTimeFormat, strtotime($mysqlDate));
2080
2081 // need to append zero for hours < 10
2082 if (strlen($time) < $appendZeroLength) {
2083 $time = '0' . $time;
2084 }
2085
2086 return [$date, $time];
2087 }
2088
2089 /**
2090 * Function get date format.
2091 *
2092 * @param string $formatType
2093 * Date name e.g. birth.
2094 *
2095 * @return string
2096 */
2097 public static function getDateFormat($formatType = NULL) {
2098 $format = NULL;
2099 if ($formatType) {
2100 $format = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_PreferencesDate',
2101 $formatType, 'date_format', 'name'
2102 );
2103 }
2104
2105 if (!$format) {
2106 $config = CRM_Core_Config::singleton();
2107 $format = $config->dateInputFormat;
2108 }
2109 return $format;
2110 }
2111
2112 /**
2113 * @param $date
2114 * @param $dateType
2115 *
2116 * @return null|string
2117 */
2118 public static function formatDate($date, $dateType) {
2119 $formattedDate = NULL;
2120 if (empty($date)) {
2121 return $formattedDate;
2122 }
2123
2124 // 1. first convert date to default format.
2125 // 2. append time to default formatted date (might be removed during format)
2126 // 3. validate date / date time.
2127 // 4. If date and time then convert to default date time format.
2128
2129 $dateKey = 'date';
2130 $dateParams = [$dateKey => $date];
2131
2132 if (CRM_Utils_Date::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2133 $dateVal = $dateParams[$dateKey];
2134 $ruleName = 'date';
2135 if ($dateType == 1) {
2136 $matches = [];
2137 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2138 $ruleName = 'dateTime';
2139 if (strpos($date, '-') !== FALSE) {
2140 $dateVal .= array_shift($matches);
2141 }
2142 }
2143 }
2144
2145 // validate date.
2146 $valid = CRM_Utils_Rule::$ruleName($dateVal);
2147
2148 if ($valid) {
2149 // format date and time to default.
2150 if ($ruleName == 'dateTime') {
2151 $dateVal = CRM_Utils_Date::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2152 // hack to add seconds
2153 $dateVal .= '00';
2154 }
2155 $formattedDate = $dateVal;
2156 }
2157 }
2158
2159 return $formattedDate;
2160 }
2161
2162 /**
2163 * Function to return days of the month.
2164 *
2165 * @return array
2166 */
2167 public static function getCalendarDayOfMonth() {
2168 $month = [];
2169 for ($i = 1; $i <= 31; $i++) {
2170 $month[$i] = $i;
2171 if ($i == 31) {
2172 $month[$i] = $i . ' / Last day of month';
2173 }
2174 }
2175 return $month;
2176 }
2177
2178 /**
2179 * Convert a relative date format to an api field.
2180 *
2181 * @param array $params
2182 * @param string $dateField
2183 * @param bool $isDatePicker
2184 * Non datepicker fields are deprecated. Exterminate Exterminate.
2185 * (but for now handle them).
2186 */
2187 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2188 if (!empty($params[$dateField . '_relative'])) {
2189 $dates = CRM_Utils_Date::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2190 unset($params[$dateField . '_relative']);
2191 }
2192 if (!empty($params[$dateField . '_low'])) {
2193 $dates[0] = $isDatePicker ? $params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2194 unset($params[$dateField . '_low']);
2195 }
2196 if (!empty($params[$dateField . '_high'])) {
2197 $dates[1] = $isDatePicker ? $params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2198 unset($params[$dateField . '_high']);
2199 }
2200 if (empty($dates)) {
2201 return;
2202 }
2203 if (empty($dates[0])) {
2204 $params[$dateField] = ['<=' => $dates[1]];
2205 }
2206 elseif (empty($dates[1])) {
2207 $params[$dateField] = ['>=' => $dates[0]];
2208 }
2209 else {
2210 $params[$dateField] = ['BETWEEN' => $dates];
2211 }
2212 }
2213
2214 /**
2215 * Print out a date object in specified format in local timezone
2216 *
2217 * @param DateTimeObject $dateObject
2218 * @param string $format
2219 * @return string
2220 */
2221 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2222 $systemTimeZone = new DateTimeZone(CRM_Core_Config::singleton()->userSystem->getTimeZoneString());
2223 $dateObject->setTimezone($systemTimeZone);
2224 return $dateObject->format($format);
2225 }
2226
2227 }