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