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