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