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