3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 class CRM_Utils_Date
{
24 * Format a date by padding it with leading '0'.
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
33 * formatted string for date
35 public static function format($date, $separator = '', $invalidDate = 0) {
36 if (is_numeric($date) &&
37 ((strlen($date) == 8) ||
(strlen($date) == 14))
42 if (!is_array($date) ||
43 CRM_Utils_System
::isNull($date) ||
49 $date['Y'] = (int ) $date['Y'];
50 if ($date['Y'] < 1000 ||
$date['Y'] > 2999) {
54 if (array_key_exists('m', $date)) {
55 $date['M'] = $date['m'];
57 elseif (array_key_exists('F', $date)) {
58 $date['M'] = $date['F'];
61 if (!empty($date['M'])) {
62 $date['M'] = (int ) $date['M'];
63 if ($date['M'] < 1 ||
$date['M'] > 12) {
71 if (!empty($date['d'])) {
72 $date['d'] = (int ) $date['d'];
78 if (!checkdate($date['M'], $date['d'], $date['Y'])) {
82 $date['M'] = sprintf('%02d', $date['M']);
83 $date['d'] = sprintf('%02d', $date['d']);
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
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;
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
104 $date['h'] = (int ) $date['h'];
110 // in 24-hour format the hour is under the 'H' key
111 if (!empty($date['H'])) {
112 $date['H'] = (int) $date['H'];
118 if (!empty($date['i'])) {
119 $date['i'] = (int ) $date['i'];
125 if ($date['h'] == 0 && $date['H'] != 0) {
126 $date['h'] = $date['H'];
129 if (!empty($date['s'])) {
130 $date['s'] = (int ) $date['s'];
136 $date['h'] = sprintf('%02d', $date['h']);
137 $date['i'] = sprintf('%02d', $date['i']);
138 $date['s'] = sprintf('%02d', $date['s']);
143 $time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
146 return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
150 * Return abbreviated weekday names according to the locale.
152 * Array will be in localized order according to 'weekBegins' setting,
153 * but array keys will always match to:
159 * 0-based array with abbreviated weekday names
162 public static function getAbbrWeekdayNames() {
163 $key = 'abbrDays_' . \CRM_Core_I18n
::getLocale();
164 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
165 $intl_formatter = IntlDateFormatter
::create(CRM_Core_I18n
::getLocale(), IntlDateFormatter
::MEDIUM
, IntlDateFormatter
::MEDIUM
, NULL, IntlDateFormatter
::GREGORIAN
, 'E');
167 0 => $intl_formatter->format(strtotime('Sunday')),
168 1 => $intl_formatter->format(strtotime('Monday')),
169 2 => $intl_formatter->format(strtotime('Tuesday')),
170 3 => $intl_formatter->format(strtotime('Wednesday')),
171 4 => $intl_formatter->format(strtotime('Thursday')),
172 5 => $intl_formatter->format(strtotime('Friday')),
173 6 => $intl_formatter->format(strtotime('Saturday')),
175 // First day of the week
176 $firstDay = Civi
::settings()->get('weekBegins');
178 \Civi
::$statics[__CLASS__
][$key] = [];
179 for ($i = $firstDay; count(\Civi
::$statics[__CLASS__
][$key]) < 7; $i = $i > 5 ?
0 : $i +
1) {
180 \Civi
::$statics[__CLASS__
][$key][$i] = $days[$i];
183 return \Civi
::$statics[__CLASS__
][$key];
187 * Return full weekday names according to the locale.
189 * Array will be in localized order according to 'weekBegins' setting,
190 * but array keys will always match to:
196 * 0-based array with full weekday names
199 public static function getFullWeekdayNames() {
200 $key = 'fullDays_' . \CRM_Core_I18n
::getLocale();
201 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
202 $intl_formatter = IntlDateFormatter
::create(CRM_Core_I18n
::getLocale(), IntlDateFormatter
::MEDIUM
, IntlDateFormatter
::MEDIUM
, NULL, IntlDateFormatter
::GREGORIAN
, 'EEEE');
204 0 => $intl_formatter->format(strtotime('Sunday')),
205 1 => $intl_formatter->format(strtotime('Monday')),
206 2 => $intl_formatter->format(strtotime('Tuesday')),
207 3 => $intl_formatter->format(strtotime('Wednesday')),
208 4 => $intl_formatter->format(strtotime('Thursday')),
209 5 => $intl_formatter->format(strtotime('Friday')),
210 6 => $intl_formatter->format(strtotime('Saturday')),
212 // First day of the week
213 $firstDay = Civi
::settings()->get('weekBegins');
215 \Civi
::$statics[__CLASS__
][$key] = [];
216 for ($i = $firstDay; count(\Civi
::$statics[__CLASS__
][$key]) < 7; $i = $i > 5 ?
0 : $i +
1) {
217 \Civi
::$statics[__CLASS__
][$key][$i] = $days[$i];
220 return \Civi
::$statics[__CLASS__
][$key];
224 * Return abbreviated month names according to the locale.
229 * 1-based array with abbreviated month names
232 public static function &getAbbrMonthNames($month = FALSE) {
233 $key = 'abbrMonthNames_' . \CRM_Core_I18n
::getLocale();
234 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
235 $intl_formatter = IntlDateFormatter
::create(CRM_Core_I18n
::getLocale(), IntlDateFormatter
::MEDIUM
, IntlDateFormatter
::MEDIUM
, NULL, IntlDateFormatter
::GREGORIAN
, 'MMM');
236 \Civi
::$statics[__CLASS__
][$key] = [
237 1 => $intl_formatter->format(strtotime('January')),
238 2 => $intl_formatter->format(strtotime('February')),
239 3 => $intl_formatter->format(strtotime('March')),
240 4 => $intl_formatter->format(strtotime('April')),
241 5 => $intl_formatter->format(strtotime('May')),
242 6 => $intl_formatter->format(strtotime('June')),
243 7 => $intl_formatter->format(strtotime('July')),
244 8 => $intl_formatter->format(strtotime('August')),
245 9 => $intl_formatter->format(strtotime('September')),
246 10 => $intl_formatter->format(strtotime('October')),
247 11 => $intl_formatter->format(strtotime('November')),
248 12 => $intl_formatter->format(strtotime('December')),
252 return \Civi
::$statics[__CLASS__
][$key][$month];
254 return \Civi
::$statics[__CLASS__
][$key];
258 * Return full month names according to the locale.
261 * 1-based array with full month names
264 public static function &getFullMonthNames() {
265 $key = 'fullMonthNames_' . \CRM_Core_I18n
::getLocale();
266 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
267 // Not relying on strftime because it depends on the operating system
268 // and most people will not have a non-US locale configured out of the box
269 // Ignoring other date names for now, since less visible by default
270 \Civi
::$statics[__CLASS__
][$key] = [
279 9 => ts('September'),
281 11 => ts('November'),
282 12 => ts('December'),
286 return \Civi
::$statics[__CLASS__
][$key];
290 * @param string $string
294 public static function unixTime($string) {
295 if (empty($string)) {
298 $parsedDate = date_parse($string);
299 return mktime(CRM_Utils_Array
::value('hour', $parsedDate),
300 CRM_Utils_Array
::value('minute', $parsedDate),
302 CRM_Utils_Array
::value('month', $parsedDate),
303 CRM_Utils_Array
::value('day', $parsedDate),
304 CRM_Utils_Array
::value('year', $parsedDate)
309 * Create a date and time string in a provided format.
310 * %A - Full day name ('Saturday'..'Sunday')
311 * %a - abbreviated day name ('Sat'..'Sun')
312 * %b - abbreviated month name ('Jan'..'Dec')
313 * %B - full month name ('January'..'December')
314 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
315 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
316 * %E - day of the month as a decimal number ('1'..'31')
317 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
318 * %H - hour in 24-hour format, 0-padded ('00'..'23')
319 * %I - hour in 12-hour format, 0-padded ('01'..'12')
320 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
321 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
322 * %m - month as a decimal number, 0-padded ('01'..'12')
323 * %M - minute, 0-padded ('00'..'60')
324 * %p - lowercase ante/post meridiem ('am', 'pm')
325 * %P - uppercase ante/post meridiem ('AM', 'PM')
326 * %Y - year as a decimal number including the century ('2005')
328 * @param string $dateString
329 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
330 * @param string $format
332 * @param array $dateParts
333 * An array with the desired date parts.
336 * the $format-formatted $date
338 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
339 // 1-based (January) month names arrays
340 $abbrMonths = self
::getAbbrMonthNames();
341 $fullMonths = self
::getFullMonthNames();
342 $fullWeekdayNames = self
::getFullWeekdayNames();
343 $abbrWeekdayNames = self
::getAbbrWeekdayNames();
346 $config = CRM_Core_Config
::singleton();
349 if (array_intersect(['h', 'H'], $dateParts)) {
350 $format = $config->dateformatDatetime
;
352 elseif (array_intersect(['d', 'j'], $dateParts)) {
353 $format = $config->dateformatFull
;
355 elseif (array_intersect(['m', 'M'], $dateParts)) {
356 $format = $config->dateformatPartial
;
359 $format = $config->dateformatYear
;
363 if (strpos(($dateString ??
''), '-')) {
364 $month = (int) substr($dateString, 5, 2);
365 $day = (int) substr($dateString, 8, 2);
368 $month = (int) substr(($dateString ??
''), 4, 2);
369 $day = (int) substr(($dateString ??
''), 6, 2);
372 if (strlen(($dateString ??
'')) > 10) {
373 $format = $config->dateformatDatetime
;
376 $format = $config->dateformatFull
;
378 elseif ($month > 0) {
379 $format = $config->dateformatPartial
;
382 $format = $config->dateformatYear
;
387 if (!CRM_Utils_System
::isNull($dateString)) {
388 if (strpos($dateString, '-')) {
389 $year = (int) substr($dateString, 0, 4);
390 $month = (int) substr($dateString, 5, 2);
391 $day = (int) substr($dateString, 8, 2);
393 $hour24 = (int) substr($dateString, 11, 2);
394 $minute = (int) substr($dateString, 14, 2);
395 $second = (int) substr($dateString, 17, 2);
398 $year = (int) substr($dateString, 0, 4);
399 $month = (int) substr($dateString, 4, 2);
400 $day = (int) substr($dateString, 6, 2);
402 $hour24 = (int) substr($dateString, 8, 2);
403 $minute = (int) substr($dateString, 10, 2);
404 $second = (int) substr($dateString, 12, 2);
407 $dayInt = date('w', strtotime($dateString));
409 if ($day %
10 == 1 and $day != 11) {
412 elseif ($day %
10 == 2 and $day != 12) {
415 elseif ($day %
10 == 3 and $day != 13) {
436 $hour12 = $hour24 - 12;
442 '%A' => $fullWeekdayNames[$dayInt] ??
NULL,
443 '%a' => $abbrWeekdayNames[$dayInt] ??
NULL,
444 '%b' => $abbrMonths[$month] ??
NULL,
445 '%B' => $fullMonths[$month] ??
NULL,
446 '%d' => $day > 9 ?
$day : '0' . $day,
447 '%e' => $day > 9 ?
$day : ' ' . $day,
450 '%H' => $hour24 > 9 ?
$hour24 : '0' . $hour24,
451 '%h' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
452 '%I' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
453 '%k' => $hour24 > 9 ?
$hour24 : ' ' . $hour24,
454 '%l' => $hour12 > 9 ?
$hour12 : ' ' . $hour12,
455 '%m' => $month > 9 ?
$month : '0' . $month,
456 '%M' => $minute > 9 ?
$minute : '0' . $minute,
457 '%i' => $minute > 9 ?
$minute : '0' . $minute,
458 '%p' => strtolower($type),
461 '%s' => str_pad($second, 2, 0, STR_PAD_LEFT
),
462 '%S' => str_pad($second, 2, 0, STR_PAD_LEFT
),
465 return strtr($format, $date);
471 * Format the field according to the site's preferred date format.
473 * This is likely to look something like December 31st, 2020.
475 * @param string $date
479 public static function formatDateOnlyLong(string $date):string {
480 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
484 * Wrapper for customFormat that takes a timestamp
486 * @param int $timestamp
487 * Date and time in timestamp format.
488 * @param string $format
490 * @param array $dateParts
491 * An array with the desired date parts.
494 * the $format-formatted $date
496 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
497 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
501 * Converts the date/datetime from MySQL format to ISO format
503 * @param string $mysql
504 * Date/datetime in MySQL format.
507 * date/datetime in ISO format
509 public static function mysqlToIso($mysql) {
510 $year = substr(($mysql ??
''), 0, 4);
511 $month = substr(($mysql ??
''), 4, 2);
512 $day = substr(($mysql ??
''), 6, 2);
513 $hour = substr(($mysql ??
''), 8, 2);
514 $minute = substr(($mysql ??
''), 10, 2);
515 $second = substr(($mysql ??
''), 12, 2);
541 * Converts the date/datetime from ISO format to MySQL format
542 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
543 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
544 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
547 * Date/datetime in ISO format.
550 * date/datetime in MySQL format
552 public static function isoToMysql($iso) {
553 $dropArray = ['-' => '', ':' => '', ' ' => ''];
554 return strtr(($iso ??
''), $dropArray);
558 * Converts the any given date to default date format.
560 * @param array $params
561 * Has given date-format.
562 * @param int $dateType
564 * @param string $dateParam
569 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
573 if (!empty($params[$dateParam])) {
574 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
575 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
580 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
586 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
592 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
598 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
604 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
610 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
616 if ($dateType == 1) {
617 $formattedDate = explode("-", $value);
618 if (count($formattedDate) == 3) {
619 $year = (int) $formattedDate[0];
620 $month = (int) $formattedDate[1];
621 $day = (int) $formattedDate[2];
623 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
631 if ($dateType == 2 ||
$dateType == 4) {
632 $formattedDate = explode("/", $value);
633 if (count($formattedDate) != 3) {
634 $formattedDate = explode("-", $value);
636 if (count($formattedDate) == 3) {
637 $year = (int) $formattedDate[2];
638 $month = (int) $formattedDate[0];
639 $day = (int) $formattedDate[1];
645 if ($dateType == 8) {
646 $dateArray = explode(' ', $value);
648 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
651 $fullMonths = self
::getFullMonthNames();
652 foreach ($fullMonths as $key => $val) {
653 if (strtolower($dateArray[0]) == strtolower($val)) {
659 $abbrMonths = self
::getAbbrMonthNames();
660 foreach ($abbrMonths as $key => $val) {
661 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
667 $year = (int) $dateArray[2];
668 $day = (int) $dateArray[1];
669 $month = (int) $monthInt;
671 if ($dateType == 16) {
672 $dateArray = explode('-', $value);
673 if (count($dateArray) != 3) {
674 $dateArray = explode('/', $value);
677 if (count($dateArray) == 3) {
679 $fullMonths = self
::getFullMonthNames();
680 foreach ($fullMonths as $key => $val) {
681 if (strtolower($dateArray[1]) == strtolower($val)) {
687 $abbrMonths = self
::getAbbrMonthNames();
688 foreach ($abbrMonths as $key => $val) {
689 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
696 $monthInt = $dateArray[1];
699 $year = (int) $dateArray[2];
700 $day = (int) $dateArray[0];
701 $month = (int) $monthInt;
707 if ($dateType == 32) {
708 $formattedDate = explode("/", $value);
709 if (count($formattedDate) == 3) {
710 $year = (int) $formattedDate[2];
711 $month = (int) $formattedDate[1];
712 $day = (int) $formattedDate[0];
719 $month = ($month < 10) ?
"0" . "$month" : $month;
720 $day = ($day < 10) ?
"0" . "$day" : $day;
724 $year = substr($now['year'], 0, 2) * 100 +
$year;
725 if ($year > ($now['year'] +
5)) {
728 elseif ($year <= ($now['year'] - 95)) {
733 if ($params[$dateParam]) {
734 $params[$dateParam] = "$year$month$day";
736 // if month is invalid return as error
737 if ($month !== '00' && $month <= 12) {
744 * Translate a TTL to a concrete expiration time.
746 * @param null|int|DateInterval $ttl
747 * @param int $default
748 * The value to use if $ttl is not specified (NULL).
750 * Timestamp (seconds since epoch).
751 * @throws \CRM_Utils_Cache_InvalidArgumentException
753 public static function convertCacheTtlToExpires($ttl, $default) {
759 return time() +
$ttl;
761 elseif ($ttl instanceof DateInterval
) {
762 return date_add(new DateTime(), $ttl)->getTimestamp();
765 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
772 * @param null|int|DateInterval $ttl
773 * @param int $default
774 * The value to use if $ttl is not specified (NULL).
776 * Seconds until expiration.
777 * @throws \CRM_Utils_Cache_InvalidArgumentException
779 public static function convertCacheTtl($ttl, $default) {
783 elseif (is_int($ttl)) {
786 elseif ($ttl instanceof DateInterval
) {
787 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
790 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
795 * @param int|false|null $timeStamp
797 * @return bool|string
799 public static function currentDBDate($timeStamp = NULL) {
800 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
809 public static function overdue($date, $now = NULL) {
810 $mysqlDate = self
::isoToMysql($date);
812 $now = self
::currentDBDate();
815 $now = self
::isoToMysql($now);
818 return !(strtotime($mysqlDate) >= strtotime($now));
822 * Get customized today.
824 * This function is used for getting customized today. To get
825 * actuall today pass 'dayParams' as null. or else pass the day,
826 * month, year values as array values
827 * Example: $dayParams = array(
828 * 'day' => '25', 'month' => '10',
829 * 'year' => '2007' );
831 * @param array $dayParams of the day, month, year.
832 * Array of the day, month, year.
834 * @param string $format
835 * Expected date format( default.
836 * format is 2007-12-21 )
839 * Return the customized today's date (Y-m-d)
841 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
842 if (is_null($dayParams) ||
empty($dayParams)) {
843 $today = date($format);
846 $today = date($format, mktime(0, 0, 0,
857 * Find whether today's date lies in
860 * @param date $startDate
861 * Start date for the range.
862 * @param date $endDate
863 * End date for the range.
866 * true if today's date is in the given date range
868 public static function getRange($startDate, $endDate) {
869 $today = date("Y-m-d");
870 $mysqlStartDate = self
::isoToMysql($startDate);
871 $mysqlEndDate = self
::isoToMysql($endDate);
872 $mysqlToday = self
::isoToMysql($today);
874 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
877 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
880 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
887 * Get start date and end from
888 * the given relative term and unit
890 * @param string $relative Relative format in the format term.unit.
893 * @param string $from
895 * @param string $fromTime
896 * @param string $toTime
899 * start date, end date
901 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
903 list($term, $unit) = explode('.', $relative, 2);
904 $dateRange = self
::relativeToAbsolute($term, $unit);
905 $from = substr(($dateRange['from'] ??
''), 0, 8);
906 $to = substr(($dateRange['to'] ??
''), 0, 8);
907 // @todo fix relativeToAbsolute & add tests
908 // relativeToAbsolute returns 8 char date strings
909 // or 14 char date + time strings.
910 // We should use those. However, it turns out to be unreliable.
911 // e.g. this.week does NOT return 235959 for 'from'
912 // so our defaults are more reliable.
913 // Currently relativeToAbsolute only supports 'whole' days so that is ok
916 $from = self
::processDate($from, $fromTime);
917 $to = self
::processDate($to, $toTime);
923 * Calculate Age in Years if greater than one year else in months.
925 * @param date $birthDate
927 * @param date $targetDate
928 * Target Date. (show age on specific date)
931 * array $results contains years or months
933 public static function calculateAge($birthDate, $targetDate = NULL) {
935 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
937 $bDate = explode('-', $formatedBirthDate);
938 $birthYear = $bDate[0];
939 $birthMonth = $bDate[1];
940 $birthDay = $bDate[2];
941 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
943 $year_diff = date("Y", $targetDate) - $birthYear;
945 // don't calculate age CRM-3143
946 if ($birthYear == '1902') {
949 switch ($year_diff) {
951 $month = (12 - $birthMonth) +
date("m", $targetDate);
953 if (date("d", $targetDate) < $birthDay) {
956 $results['months'] = $month;
958 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
959 $results['months'] = $month - 1;
962 $results['years'] = $year_diff;
967 $month = date("m", $targetDate) - $birthMonth;
968 $results['months'] = $month;
972 $results['years'] = $year_diff;
973 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
982 * Calculate next payment date according to provided unit & interval
984 * @param string $unit
985 * Frequency unit like year,month, week etc.
987 * @param int $interval
988 * Frequency interval.
991 * Start date of pledge.
993 * @param bool $dontCareTime
996 * contains new date with added interval
998 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
999 if (is_array($date)) {
1000 $hour = $date['H'] ??
'00';
1001 $minute = $date['i'] ??
'00';
1002 $second = $date['s'] ??
'00';
1003 $month = $date['M'] ??
NULL;
1004 $day = $date['d'] ??
NULL;
1005 $year = $date['Y'] ??
NULL;
1008 extract(date_parse($date));
1010 $date = mktime($hour, $minute, $second, $month, $day, $year);
1013 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
1017 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
1021 $interval = $interval * 7;
1022 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1026 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1030 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1034 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1037 $date['M'] = $scheduleDate[0];
1038 $date['d'] = $scheduleDate[1];
1039 $date['Y'] = $scheduleDate[2];
1040 if ($dontCareTime == FALSE) {
1041 $date['H'] = $scheduleDate[3];
1042 $date['i'] = $scheduleDate[4];
1043 $date['s'] = $scheduleDate[5];
1049 * Get the smarty view presentation mapping for the given format.
1051 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1052 * they should be rendered using a longer date format. This is likely as much to
1053 * do with the earlier date widget being unable to handle some formats as usablity.
1054 * However, we continue to respect this.
1057 * Given format ( eg 'M Y', 'Y M' ).
1059 * @return string|null
1060 * Smarty translation of the date format. Null is also valid and is translated
1061 * according to the available parts at the smarty layer.
1063 public static function getDateFieldViewFormat($format) {
1064 $supportableFormats = [
1065 'mm/dd' => '%B %E%f',
1066 'dd-mm' => '%E%f %B',
1070 'dd/mm/yy' => '%E%f %B %Y',
1073 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1077 * Pick the smarty format from settings that best matches the time string we have.
1079 * For view purposes we historically use the setting that most closely matches the data
1080 * in the format from our settings, as opposed to the setting configured for the field.
1085 public static function pickBestSmartyFormat($format) {
1086 if (stristr($format, 'h')) {
1087 return Civi
::settings()->get('dateformatDatetime');
1089 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1090 return Civi
::settings()->get('dateformatFull');
1092 if (stristr($format, 'm')) {
1093 return Civi
::settings()->get('dateformatPartial');
1095 return Civi
::settings()->get('dateformatYear');
1099 * Map date plugin and actual format that is used by PHP.
1103 public static function datePluginToPHPFormats() {
1104 $dateInputFormats = [
1105 "mm/dd/yy" => 'm/d/Y',
1106 "dd/mm/yy" => 'd/m/Y',
1107 "yy-mm-dd" => 'Y-m-d',
1108 "dd-mm-yy" => 'd-m-Y',
1109 "dd.mm.yy" => 'd.m.Y',
1111 "M d, yy" => 'M j, Y',
1112 "d M yy" => 'j M Y',
1113 "MM d, yy" => 'F j, Y',
1114 "d MM yy" => 'j F Y',
1115 "DD, d MM yy" => 'l, j F Y',
1123 return $dateInputFormats;
1127 * Resolves the given relative time interval into finite time limits.
1129 * @param string $relativeTerm
1130 * Relative time frame: this, previous, previous_1.
1132 * Frequency unit like year, month, week etc.
1135 * start date and end date for the relative time frame
1137 public static function relativeToAbsolute($relativeTerm, $unit) {
1139 $from = $to = $dateRange = [];
1140 $from['H'] = $from['i'] = $from['s'] = 0;
1141 $relativeTermParts = explode('_', $relativeTerm);
1142 $relativeTermPrefix = $relativeTermParts[0];
1143 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1147 switch ($relativeTerm) {
1149 $from['M'] = $from['d'] = 1;
1152 $to['Y'] = $from['Y'] = $now['year'] - 1;
1155 case 'previous_before':
1156 $from['M'] = $from['d'] = 1;
1159 $to['Y'] = $from['Y'] = $now['year'] - 2;
1163 $from['M'] = $from['d'] = 1;
1166 $from['Y'] = $now['year'] - 2;
1167 $to['Y'] = $now['year'] - 1;
1173 $to['Y'] = $now['year'] - 1;
1178 $from['M'] = $from['d'] = 1;
1179 $from['Y'] = $now['year'];
1183 case 'greater_previous':
1186 $from['Y'] = $now['year'] - 1;
1191 $to['d'] = $now['mday'];
1192 $to['M'] = $now['mon'];
1193 $to['Y'] = $now['year'];
1195 $to['i'] = $to['s'] = 59;
1196 $from = self
::intervalAdd('year', -1, $to);
1197 $from = self
::intervalAdd('second', 1, $from);
1201 $from['M'] = $from['d'] = 1;
1202 $from['Y'] = $now['year'];
1204 $to['i'] = $to['s'] = 59;
1205 $to['d'] = $now['mday'];
1206 $to['M'] = $now['mon'];
1207 $to['Y'] = $now['year'];
1211 $to['d'] = $now['mday'];
1212 $to['M'] = $now['mon'];
1213 $to['Y'] = $now['year'];
1215 $to['i'] = $to['s'] = 59;
1216 $from = self
::intervalAdd('year', -2, $to);
1217 $from = self
::intervalAdd('second', 1, $from);
1221 $to['d'] = $now['mday'];
1222 $to['M'] = $now['mon'];
1223 $to['Y'] = $now['year'];
1225 $to['i'] = $to['s'] = 59;
1226 $from = self
::intervalAdd('year', -3, $to);
1227 $from = self
::intervalAdd('second', 1, $from);
1233 $to['Y'] = $now['year'];
1238 $from['M'] = $from['d'] = 1;
1241 $to['Y'] = $from['Y'] = $now['year'] +
1;
1245 $from['d'] = $now['mday'];
1246 $from['M'] = $now['mon'];
1247 $from['Y'] = $now['year'];
1248 $to['d'] = $now['mday'] - 1;
1249 $to['M'] = $now['mon'];
1250 $to['Y'] = $now['year'] +
1;
1254 switch ($relativeTermPrefix) {
1257 $to['d'] = $now['mday'];
1258 $to['M'] = $now['mon'];
1259 $to['Y'] = $now['year'];
1261 $to['i'] = $to['s'] = 59;
1262 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1263 $from = self
::intervalAdd('second', 1, $from);
1267 $from['d'] = $from['M'] = 1;
1270 $to['Y'] = $from['Y'] = $now['year'];
1271 if (is_numeric($relativeTermSuffix)) {
1272 $from['Y'] -= ($relativeTermSuffix - 1);
1281 $config = CRM_Core_Config
::singleton();
1282 $from['d'] = $config->fiscalYearStart
['d'];
1283 $from['M'] = $config->fiscalYearStart
['M'];
1284 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1285 switch ($relativeTermPrefix) {
1287 $from['Y'] = $fYear;
1288 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1289 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1290 $to['d'] = $fiscalEnd['2'];
1291 $to['M'] = $fiscalEnd['1'];
1292 $to['Y'] = $fiscalEnd['0'];
1294 $to['i'] = $to['s'] = 59;
1295 if (is_numeric($relativeTermSuffix)) {
1296 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1297 $from = self
::intervalAdd('second', 1, $from);
1302 if (!is_numeric($relativeTermSuffix)) {
1303 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1304 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1305 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1306 $to['d'] = $fiscalEnd['2'];
1307 $to['M'] = $fiscalEnd['1'];
1308 $to['Y'] = $fiscalEnd['0'];
1310 $to['i'] = $to['s'] = 59;
1313 $from['Y'] = $fYear - $relativeTermSuffix;
1314 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1315 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1316 $to['d'] = $fiscalEnd['2'];
1317 $to['M'] = $fiscalEnd['1'];
1320 $to['i'] = $to['s'] = 59;
1325 $from['Y'] = $fYear +
1;
1326 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1327 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1328 $to['d'] = $fiscalEnd['2'];
1329 $to['M'] = $fiscalEnd['1'];
1330 $to['Y'] = $fiscalEnd['0'];
1336 switch ($relativeTerm) {
1339 $quarter = ceil($now['mon'] / 3);
1341 $from['M'] = (3 * $quarter) - 2;
1342 $to['M'] = 3 * $quarter;
1343 $to['Y'] = $from['Y'] = $now['year'];
1344 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1349 $quarter = ceil($now['mon'] / 3);
1350 $quarter = $quarter - $difference;
1352 if ($quarter <= 0) {
1357 $from['M'] = (3 * $quarter) - 2;
1358 $to['M'] = 3 * $quarter;
1359 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1360 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1363 case 'previous_before':
1365 $quarter = ceil($now['mon'] / 3);
1366 $quarter = $quarter - $difference;
1368 if ($quarter <= 0) {
1373 $from['M'] = (3 * $quarter) - 2;
1374 $to['M'] = 3 * $quarter;
1375 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1376 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1381 $quarter = ceil($now['mon'] / 3);
1382 $current_quarter = $quarter;
1383 $quarter = $quarter - $difference;
1385 if ($quarter <= 0) {
1390 $from['M'] = (3 * $quarter) - 2;
1391 switch ($current_quarter) {
1393 $to['M'] = (4 * $quarter);
1397 $to['M'] = (4 * $quarter) +
3;
1401 $to['M'] = (4 * $quarter) +
2;
1405 $to['M'] = (4 * $quarter) +
1;
1408 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1409 if ($to['M'] > 12) {
1410 $to['M'] = 3 * ($quarter - 3);
1411 $to['Y'] = $now['year'];
1413 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1417 $quarter = ceil($now['mon'] / 3) - 1;
1419 if ($quarter <= 0) {
1423 $to['M'] = 3 * $quarter;
1424 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1425 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1430 $quarter = ceil($now['mon'] / 3);
1432 $from['M'] = (3 * $quarter) - 2;
1433 $from['Y'] = $now['year'];
1437 case 'greater_previous':
1438 $quarter = ceil($now['mon'] / 3) - 1;
1440 if ($quarter <= 0) {
1444 $from['M'] = 3 * $quarter;
1445 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1446 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1451 $to['d'] = $now['mday'];
1452 $to['M'] = $now['mon'];
1453 $to['Y'] = $now['year'];
1455 $to['i'] = $to['s'] = 59;
1456 $from = self
::intervalAdd('day', -90, $to);
1457 $from = self
::intervalAdd('second', 1, $from);
1461 $quarter = ceil($now['mon'] / 3);
1463 $from['M'] = (3 * $quarter) - 2;
1464 $from['Y'] = $now['year'];
1465 $to['d'] = $now['mday'];
1466 $to['M'] = $now['mon'];
1467 $to['Y'] = $now['year'];
1469 $to['i'] = $to['s'] = 59;
1473 $quarter = ceil($now['mon'] / 3);
1474 $to['M'] = 3 * $quarter;
1475 $to['Y'] = $now['year'];
1476 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1483 $quarter = ceil($now['mon'] / 3);
1484 $quarter = $quarter - $difference;
1487 $now['year'] = $now['year'] +
1;
1490 if ($quarter <= 0) {
1495 $from['M'] = (3 * $quarter) - 2;
1496 $to['M'] = 3 * $quarter;
1497 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1498 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1502 $from['d'] = $now['mday'];
1503 $from['M'] = $now['mon'];
1504 $from['Y'] = $now['year'];
1506 $from['i'] = $to['s'] = 00;
1507 $to = self
::intervalAdd('day', 90, $from);
1508 $to = self
::intervalAdd('second', -1, $to);
1512 if ($relativeTermPrefix === 'ending') {
1513 $to['d'] = $now['mday'];
1514 $to['M'] = $now['mon'];
1515 $to['Y'] = $now['year'];
1517 $to['i'] = $to['s'] = 59;
1518 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1519 $from = self
::intervalAdd('second', 1, $from);
1525 switch ($relativeTerm) {
1528 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1529 $from['M'] = $to['M'] = $now['mon'];
1530 $from['Y'] = $to['Y'] = $now['year'];
1535 if ($now['mon'] == 1) {
1536 $from['M'] = $to['M'] = 12;
1537 $from['Y'] = $to['Y'] = $now['year'] - 1;
1540 $from['M'] = $to['M'] = $now['mon'] - 1;
1541 $from['Y'] = $to['Y'] = $now['year'];
1543 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1546 case 'previous_before':
1548 if ($now['mon'] < 3) {
1549 $from['M'] = $to['M'] = 10 +
$now['mon'];
1550 $from['Y'] = $to['Y'] = $now['year'] - 1;
1553 $from['M'] = $to['M'] = $now['mon'] - 2;
1554 $from['Y'] = $to['Y'] = $now['year'];
1556 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1561 if ($now['mon'] < 3) {
1562 $from['M'] = 10 +
$now['mon'];
1563 $from['Y'] = $now['year'] - 1;
1566 $from['M'] = $now['mon'] - 2;
1567 $from['Y'] = $now['year'];
1570 if ($now['mon'] == 1) {
1572 $to['Y'] = $now['year'] - 1;
1575 $to['M'] = $now['mon'] - 1;
1576 $to['Y'] = $now['year'];
1579 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1583 // before end of past month
1584 if ($now['mon'] == 1) {
1586 $to['Y'] = $now['year'] - 1;
1589 $to['M'] = $now['mon'] - 1;
1590 $to['Y'] = $now['year'];
1593 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1599 $from['M'] = $now['mon'];
1600 $from['Y'] = $now['year'];
1604 case 'greater_previous':
1605 // from end of past month
1606 if ($now['mon'] == 1) {
1608 $from['Y'] = $now['year'] - 1;
1611 $from['M'] = $now['mon'] - 1;
1612 $from['Y'] = $now['year'];
1615 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1620 $to['d'] = $now['mday'];
1621 $to['M'] = $now['mon'];
1622 $to['Y'] = $now['year'];
1624 $to['i'] = $to['s'] = 59;
1625 $from = self
::intervalAdd('day', -60, $to);
1626 $from = self
::intervalAdd('second', 1, $from);
1630 $to['d'] = $now['mday'];
1631 $to['M'] = $now['mon'];
1632 $to['Y'] = $now['year'];
1634 $to['i'] = $to['s'] = 59;
1635 $from = self
::intervalAdd('day', -30, $to);
1636 $from = self
::intervalAdd('second', 1, $from);
1641 $from['M'] = $now['mon'];
1642 $from['Y'] = $now['year'];
1643 $to['d'] = $now['mday'];
1644 $to['M'] = $now['mon'];
1645 $to['Y'] = $now['year'];
1647 $to['i'] = $to['s'] = 59;
1652 $to['Y'] = $now['year'];
1653 $to['M'] = $now['mon'];
1654 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1660 if ($now['mon'] == 12) {
1661 $from['M'] = $to['M'] = 1;
1662 $from['Y'] = $to['Y'] = $now['year'] +
1;
1665 $from['M'] = $to['M'] = $now['mon'] +
1;
1666 $from['Y'] = $to['Y'] = $now['year'];
1668 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1672 $from['d'] = $now['mday'];
1673 $from['M'] = $now['mon'];
1674 $from['Y'] = $now['year'];
1676 $from['i'] = $to['s'] = 00;
1677 $to = self
::intervalAdd('day', 30, $from);
1678 $to = self
::intervalAdd('second', -1, $to);
1682 $from['d'] = $now['mday'];
1683 $from['M'] = $now['mon'];
1684 $from['Y'] = $now['year'];
1686 $from['i'] = $to['s'] = 00;
1687 $to = self
::intervalAdd('day', 60, $from);
1688 $to = self
::intervalAdd('second', -1, $to);
1692 if ($relativeTermPrefix === 'ending') {
1693 $to['d'] = $now['mday'];
1694 $to['M'] = $now['mon'];
1695 $to['Y'] = $now['year'];
1697 $to['i'] = $to['s'] = 59;
1698 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1699 $from = self
::intervalAdd('second', 1, $from);
1705 $weekFirst = Civi
::settings()->get('weekBegins');
1706 $thisDay = $now['wday'];
1707 if ($weekFirst > $thisDay) {
1708 $diffDay = $thisDay - $weekFirst +
7;
1711 $diffDay = $thisDay - $weekFirst;
1713 switch ($relativeTerm) {
1715 $from['d'] = $now['mday'];
1716 $from['M'] = $now['mon'];
1717 $from['Y'] = $now['year'];
1718 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1719 $to = self
::intervalAdd('day', 6, $from);
1723 $from['d'] = $now['mday'];
1724 $from['M'] = $now['mon'];
1725 $from['Y'] = $now['year'];
1726 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1727 $to = self
::intervalAdd('day', 6, $from);
1730 case 'previous_before':
1731 $from['d'] = $now['mday'];
1732 $from['M'] = $now['mon'];
1733 $from['Y'] = $now['year'];
1734 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1735 $to = self
::intervalAdd('day', 6, $from);
1739 $from['d'] = $now['mday'];
1740 $from['M'] = $now['mon'];
1741 $from['Y'] = $now['year'];
1742 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1743 $to = self
::intervalAdd('day', 13, $from);
1747 $to['d'] = $now['mday'];
1748 $to['M'] = $now['mon'];
1749 $to['Y'] = $now['year'];
1750 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1755 $from['d'] = $now['mday'];
1756 $from['M'] = $now['mon'];
1757 $from['Y'] = $now['year'];
1758 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1762 case 'greater_previous':
1763 $from['d'] = $now['mday'];
1764 $from['M'] = $now['mon'];
1765 $from['Y'] = $now['year'];
1766 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1771 $to['d'] = $now['mday'];
1772 $to['M'] = $now['mon'];
1773 $to['Y'] = $now['year'];
1775 $to['i'] = $to['s'] = 59;
1776 $from = self
::intervalAdd('day', -7, $to);
1777 $from = self
::intervalAdd('second', 1, $from);
1781 $from['d'] = $now['mday'];
1782 $from['M'] = $now['mon'];
1783 $from['Y'] = $now['year'];
1784 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1785 $to['d'] = $now['mday'];
1786 $to['M'] = $now['mon'];
1787 $to['Y'] = $now['year'];
1789 $to['i'] = $to['s'] = 59;
1793 $to['d'] = $now['mday'];
1794 $to['M'] = $now['mon'];
1795 $to['Y'] = $now['year'];
1797 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1802 $from['d'] = $now['mday'];
1803 $from['M'] = $now['mon'];
1804 $from['Y'] = $now['year'];
1805 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1806 $to = self
::intervalAdd('day', 6, $from);
1810 $from['d'] = $now['mday'];
1811 $from['M'] = $now['mon'];
1812 $from['Y'] = $now['year'];
1814 $from['i'] = $to['s'] = 00;
1815 $to = self
::intervalAdd('day', 7, $from);
1816 $to = self
::intervalAdd('second', -1, $to);
1820 if ($relativeTermPrefix === 'ending') {
1821 $to['d'] = $now['mday'];
1822 $to['M'] = $now['mon'];
1823 $to['Y'] = $now['year'];
1825 $to['i'] = $to['s'] = 59;
1826 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1827 $from = self
::intervalAdd('second', 1, $from);
1833 switch ($relativeTerm) {
1835 $from['d'] = $to['d'] = $now['mday'];
1836 $from['M'] = $to['M'] = $now['mon'];
1837 $from['Y'] = $to['Y'] = $now['year'];
1841 $from['d'] = $now['mday'];
1842 $from['M'] = $now['mon'];
1843 $from['Y'] = $now['year'];
1844 $from = self
::intervalAdd('day', -1, $from);
1845 $to['d'] = $from['d'];
1846 $to['M'] = $from['M'];
1847 $to['Y'] = $from['Y'];
1850 case 'previous_before':
1851 $from['d'] = $now['mday'];
1852 $from['M'] = $now['mon'];
1853 $from['Y'] = $now['year'];
1854 $from = self
::intervalAdd('day', -2, $from);
1855 $to['d'] = $from['d'];
1856 $to['M'] = $from['M'];
1857 $to['Y'] = $from['Y'];
1861 $from['d'] = $to['d'] = $now['mday'];
1862 $from['M'] = $to['M'] = $now['mon'];
1863 $from['Y'] = $to['Y'] = $now['year'];
1864 $from = self
::intervalAdd('day', -2, $from);
1865 $to = self
::intervalAdd('day', -1, $to);
1869 $to['d'] = $now['mday'];
1870 $to['M'] = $now['mon'];
1871 $to['Y'] = $now['year'];
1872 $to = self
::intervalAdd('day', -1, $to);
1877 $from['d'] = $now['mday'];
1878 $from['M'] = $now['mon'];
1879 $from['Y'] = $now['year'];
1884 $to['d'] = $now['mday'];
1885 $to['M'] = $now['mon'];
1886 $to['Y'] = $now['year'];
1887 $to = self
::intervalAdd('day', 1, $to);
1888 $from['d'] = $to['d'];
1889 $from['M'] = $to['M'];
1890 $from['Y'] = $to['Y'];
1894 if ($relativeTermPrefix === 'ending') {
1895 $to['d'] = $now['mday'];
1896 $to['M'] = $now['mon'];
1897 $to['Y'] = $now['year'];
1899 $to['i'] = $to['s'] = 59;
1900 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1901 $from = self
::intervalAdd('second', 1, $from);
1907 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1908 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1913 * Calculate current fiscal year based on the fiscal month and day.
1915 * @param int $fyDate
1916 * Fiscal start date.
1918 * @param int $fyMonth
1919 * Fiscal Start Month.
1922 * $fy Current Fiscal Year
1924 public static function calculateFiscalYear($fyDate, $fyMonth) {
1925 $date = date("Y-m-d");
1926 $currentYear = date("Y");
1928 // recalculate the date because month 4::04 make the difference
1929 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1930 $fyDate = $fiscalYear[2];
1931 $fyMonth = $fiscalYear[1];
1932 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1934 if ($fyStartDate > $date) {
1935 $fy = intval(intval($currentYear) - 1);
1938 $fy = intval($currentYear);
1944 * Function to process date, convert to mysql format
1946 * @param string $date
1948 * @param string $time
1950 * @param bool|string $returnNullString 'null' needs to be returned
1951 * so that db oject will set null in db
1952 * @param string $format
1953 * Expected return date format.( default is mysql ).
1956 * date format that is excepted by mysql
1958 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1961 if ($returnNullString) {
1962 $mysqlDate = 'null';
1965 if (trim($date ??
'')) {
1966 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1973 * Add the metadata about a date field to the field.
1975 * This metadata will work with the call $form->add('datepicker', ...
1977 * @param array $fieldMetaData
1978 * @param array $field
1982 public static function addDateMetadataToField($fieldMetaData, $field) {
1983 if (isset($fieldMetaData['html'])) {
1984 $field['html_type'] = $fieldMetaData['html']['type'];
1985 if ($field['html_type'] === 'Select Date') {
1986 if (!isset($field['date_format'])) {
1987 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1988 $field['start_date_years'] = $dateAttributes['minYear'];
1989 $field['end_date_years'] = $dateAttributes['maxYear'];
1990 $field['date_format'] = $dateAttributes['format'];
1991 $field['is_datetime_field'] = TRUE;
1992 $field['time_format'] = $dateAttributes['time'];
1993 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1995 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1996 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
2003 * Get the fields required for the 'extra' parameter when adding a datepicker.
2005 * @param array $field
2009 public static function getDatePickerExtra($field) {
2011 if (isset($field['date_format'])) {
2012 $extra['date'] = $field['date_format'];
2013 $extra['time'] = $field['time_format'];
2015 $thisYear = date('Y');
2016 if (isset($field['start_date_years'])) {
2017 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
2019 if (isset($field['end_date_years'])) {
2020 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
2026 * Get the attributes parameters required for datepicker.
2028 * @param array $field
2032 * Array ready to pass to $this->addForm('datepicker' as attributes.
2034 public static function getDatePickerAttributes(&$field) {
2037 'start_date_years' => 'minYear',
2038 'end_date_years' => 'maxYear',
2039 'date_format' => 'format',
2041 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2042 if (isset($field[$dateAttribute])) {
2043 $attributes[$mapTo] = $field[$dateAttribute];
2050 * Function to convert mysql to date plugin format.
2052 * @param string $mysqlDate
2055 * @param null $formatType
2056 * @param null $format
2057 * @param null $timeFormat
2062 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2063 // if date is not passed assume it as today
2065 $mysqlDate = date('Y-m-d G:i:s');
2068 $config = CRM_Core_Config
::singleton();
2070 // get actual format
2071 $params = ['name' => $formatType];
2073 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2075 if ($values['date_format']) {
2076 $format = $values['date_format'];
2079 if (isset($values['time_format'])) {
2080 $timeFormat = $values['time_format'];
2084 $dateFormat = 'm/d/Y';
2085 $date = date($dateFormat, strtotime($mysqlDate));
2088 $timeFormat = $config->timeInputFormat
;
2091 $actualTimeFormat = "g:iA";
2092 $appendZeroLength = 7;
2093 if ($timeFormat > 1) {
2094 $actualTimeFormat = "G:i";
2095 $appendZeroLength = 5;
2098 $time = date($actualTimeFormat, strtotime($mysqlDate));
2100 // need to append zero for hours < 10
2101 if (strlen($time) < $appendZeroLength) {
2102 $time = '0' . $time;
2105 return [$date, $time];
2109 * Function get date format.
2111 * @param string $formatType
2112 * Date name e.g. birth.
2116 public static function getDateFormat($formatType = NULL) {
2119 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2120 $formatType, 'date_format', 'name'
2125 $config = CRM_Core_Config
::singleton();
2126 $format = $config->dateInputFormat
;
2132 * Date formatting for imports where date format is specified.
2134 * Note this is used for imports (only) because the importer can
2135 * specify the format.
2137 * Tests are in CRM_Utils_DateTest::testFormatDate
2140 * Date string as entered.
2142 * One of the constants like CRM_Core_Form_Date::DATE_yyyy_mm_dd.
2144 * @return null|string
2146 public static function formatDate($date, $dateType) {
2151 // 1. first convert date to default format.
2152 // 2. append time to default formatted date (might be removed during format)
2153 // 3. validate date / date time.
2154 // 4. If date and time then convert to default date time format.
2157 $dateParams = [$dateKey => $date];
2159 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2160 $dateVal = $dateParams[$dateKey];
2161 if ($dateType == 1) {
2163 // The seconds part of this regex is not quite right - but it does succeed
2164 // in clarifying whether there is a time component or not - which is all it is meant
2166 if (preg_match('/(\s(([01]\d)|[2][0-3]):([0-5]\d):?[0-5]?\d?)$/', $date, $matches)) {
2167 if (strpos($date, '-') !== FALSE) {
2168 $dateVal .= array_shift($matches);
2170 if (!CRM_Utils_Rule
::dateTime($dateVal)) {
2173 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", '', $dateVal), '%Y%m%d%H%i%s');
2179 return CRM_Utils_Rule
::date($dateVal) ?
$dateVal : NULL;
2186 * Function to return days of the month.
2190 public static function getCalendarDayOfMonth() {
2192 for ($i = 1; $i <= 31; $i++
) {
2195 $month[$i] = $i . ' / Last day of month';
2202 * Convert a relative date format to an api field.
2204 * @param array $params
2205 * @param string $dateField
2206 * @param bool $isDatePicker
2207 * Non datepicker fields are deprecated. Exterminate Exterminate.
2208 * (but for now handle them).
2210 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2211 if (!empty($params[$dateField . '_relative'])) {
2212 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2213 unset($params[$dateField . '_relative']);
2215 if (!empty($params[$dateField . '_low'])) {
2216 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2217 unset($params[$dateField . '_low']);
2219 if (!empty($params[$dateField . '_high'])) {
2220 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2221 unset($params[$dateField . '_high']);
2223 if (empty($dates)) {
2226 if (empty($dates[0])) {
2227 $params[$dateField] = ['<=' => $dates[1]];
2229 elseif (empty($dates[1])) {
2230 $params[$dateField] = ['>=' => $dates[0]];
2233 $params[$dateField] = ['BETWEEN' => $dates];
2238 * Print out a date object in specified format in local timezone
2240 * @param DateTimeObject $dateObject
2241 * @param string $format
2244 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2245 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2246 $dateObject->setTimezone($systemTimeZone);
2247 return $dateObject->format($format);
2251 * Check if the value returned by a date picker has a date section (ie: includes
2252 * a '-' character) if it includes a time section (ie: includes a ':').
2254 * @param string $value
2255 * A date/time string input from a datepicker value.
2258 * TRUE if valid, FALSE if there is a time without a date.
2260 public static function datePickerValueWithTimeHasDate($value) {
2261 // If there's no : (time) or a : and a - (date) then return true
2263 strpos($value, ':') === FALSE
2264 ||
strpos($value, ':') !== FALSE && strpos($value, '-') !== FALSE
2269 * Validate start and end dates entered on a form to make sure they are
2270 * logical. Expects the form keys to be start_date and end_date.
2272 * @param string $startFormKey
2273 * The form element key of the 'start date'
2274 * @param string $startValue
2275 * The value of the 'start date'
2276 * @param string $endFormKey
2277 * The form element key of the 'end date'
2278 * @param string $endValue
2279 * The value of the 'end date'
2281 * @return array|bool
2282 * TRUE if valid, an array of the erroneous form key, and error message to
2285 public static function validateStartEndDatepickerInputs($startFormKey, $startValue, $endFormKey, $endValue) {
2287 // Check date as well as time is set
2288 if (!empty($startValue) && !self
::datePickerValueWithTimeHasDate($startValue)) {
2289 return ['key' => $startFormKey, 'message' => ts('Please enter a date as well as a time.')];
2291 if (!empty($endValue) && !self
::datePickerValueWithTimeHasDate($endValue)) {
2292 return ['key' => $endFormKey, 'message' => ts('Please enter a date as well as a time.')];
2295 // Check end date is after start date
2296 if (!empty($startValue) && !empty($endValue) && $endValue < $startValue) {
2297 return ['key' => $endFormKey, 'message' => ts('The end date should be after the start date.')];