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