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 $days = &\Civi
::$statics[__CLASS__
][$key];
167 // First day of the week
168 $firstDay = Civi
::settings()->get('weekBegins');
170 // set LC_TIME and build the arrays from locale-provided names
171 // June 1st, 1970 was a Monday
172 CRM_Core_I18n
::setLcTime();
173 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
174 $days[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
181 * Return full weekday names according to the locale.
183 * Array will be in localized order according to 'weekBegins' setting,
184 * but array keys will always match to:
190 * 0-based array with full weekday names
193 public static function getFullWeekdayNames() {
194 $key = 'fullDays_' . \CRM_Core_I18n
::getLocale();
195 $days = &\Civi
::$statics[__CLASS__
][$key];
198 // First day of the week
199 $firstDay = Civi
::settings()->get('weekBegins');
201 // set LC_TIME and build the arrays from locale-provided names
202 // June 1st, 1970 was a Monday
203 CRM_Core_I18n
::setLcTime();
204 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
205 $days[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
212 * Return abbreviated month names according to the locale.
217 * 1-based array with abbreviated month names
220 public static function &getAbbrMonthNames($month = FALSE) {
221 $key = 'abbrMonthNames_' . \CRM_Core_I18n
::getLocale();
222 $abbrMonthNames = &\Civi
::$statics[__CLASS__
][$key];
223 if (!isset($abbrMonthNames)) {
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));
232 return $abbrMonthNames[$month];
234 return $abbrMonthNames;
238 * Return full month names according to the locale.
241 * 1-based array with full month names
244 public static function &getFullMonthNames() {
245 $key = 'fullMonthNames_' . \CRM_Core_I18n
::getLocale();
246 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
247 // Not relying on strftime because it depends on the operating system
248 // and most people will not have a non-US locale configured out of the box
249 // Ignoring other date names for now, since less visible by default
250 \Civi
::$statics[__CLASS__
][$key] = [
259 9 => ts('September'),
261 11 => ts('November'),
262 12 => ts('December'),
266 return \Civi
::$statics[__CLASS__
][$key];
270 * @param string $string
274 public static function unixTime($string) {
275 if (empty($string)) {
278 $parsedDate = date_parse($string);
279 return mktime(CRM_Utils_Array
::value('hour', $parsedDate),
280 CRM_Utils_Array
::value('minute', $parsedDate),
282 CRM_Utils_Array
::value('month', $parsedDate),
283 CRM_Utils_Array
::value('day', $parsedDate),
284 CRM_Utils_Array
::value('year', $parsedDate)
289 * Create a date and time string in a provided format.
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')
307 * @param string $dateString
308 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
309 * @param string $format
311 * @param array $dateParts
312 * An array with the desired date parts.
315 * the $format-formatted $date
317 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
318 // 1-based (January) month names arrays
319 $abbrMonths = self
::getAbbrMonthNames();
320 $fullMonths = self
::getFullMonthNames();
323 $config = CRM_Core_Config
::singleton();
326 if (array_intersect(['h', 'H'], $dateParts)) {
327 $format = $config->dateformatDatetime
;
329 elseif (array_intersect(['d', 'j'], $dateParts)) {
330 $format = $config->dateformatFull
;
332 elseif (array_intersect(['m', 'M'], $dateParts)) {
333 $format = $config->dateformatPartial
;
336 $format = $config->dateformatYear
;
340 if (strpos($dateString, '-')) {
341 $month = (int) substr($dateString, 5, 2);
342 $day = (int) substr($dateString, 8, 2);
345 $month = (int) substr($dateString, 4, 2);
346 $day = (int) substr($dateString, 6, 2);
349 if (strlen($dateString) > 10) {
350 $format = $config->dateformatDatetime
;
353 $format = $config->dateformatFull
;
355 elseif ($month > 0) {
356 $format = $config->dateformatPartial
;
359 $format = $config->dateformatYear
;
364 if (!CRM_Utils_System
::isNull($dateString)) {
365 if (strpos($dateString, '-')) {
366 $year = (int) substr($dateString, 0, 4);
367 $month = (int) substr($dateString, 5, 2);
368 $day = (int) substr($dateString, 8, 2);
370 $hour24 = (int) substr($dateString, 11, 2);
371 $minute = (int) substr($dateString, 14, 2);
374 $year = (int) substr($dateString, 0, 4);
375 $month = (int) substr($dateString, 4, 2);
376 $day = (int) substr($dateString, 6, 2);
378 $hour24 = (int) substr($dateString, 8, 2);
379 $minute = (int) substr($dateString, 10, 2);
382 if ($day %
10 == 1 and $day != 11) {
385 elseif ($day %
10 == 2 and $day != 12) {
388 elseif ($day %
10 == 3 and $day != 13) {
409 $hour12 = $hour24 - 12;
415 '%b' => $abbrMonths[$month] ??
NULL,
416 '%B' => $fullMonths[$month] ??
NULL,
417 '%d' => $day > 9 ?
$day : '0' . $day,
418 '%e' => $day > 9 ?
$day : ' ' . $day,
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),
435 return strtr($format, $date);
443 * Format the field according to the site's preferred date format.
445 * This is likely to look something like December 31st, 2020.
447 * @param string $date
451 public static function formatDateOnlyLong(string $date):string {
452 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
456 * Wrapper for customFormat that takes a timestamp
458 * @param int $timestamp
459 * Date and time in timestamp format.
460 * @param string $format
462 * @param array $dateParts
463 * An array with the desired date parts.
466 * the $format-formatted $date
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);
473 * Converts the date/datetime from MySQL format to ISO format
475 * @param string $mysql
476 * Date/datetime in MySQL format.
479 * date/datetime in ISO format
481 public static function mysqlToIso($mysql) {
482 $year = substr($mysql, 0, 4);
483 $month = substr($mysql, 4, 2);
484 $day = substr($mysql, 6, 2);
485 $hour = substr($mysql, 8, 2);
486 $minute = substr($mysql, 10, 2);
487 $second = substr($mysql, 12, 2);
513 * Converts the date/datetime from ISO format to MySQL format
514 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
515 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
516 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
519 * Date/datetime in ISO format.
522 * date/datetime in MySQL format
524 public static function isoToMysql($iso) {
525 $dropArray = ['-' => '', ':' => '', ' ' => ''];
526 return strtr($iso, $dropArray);
530 * Converts the any given date to default date format.
532 * @param array $params
533 * Has given date-format.
534 * @param int $dateType
536 * @param string $dateParam
541 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
545 if (!empty($params[$dateParam])) {
546 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
547 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
552 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
558 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
564 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
570 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
576 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
582 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
588 if ($dateType == 1) {
589 $formattedDate = explode("-", $value);
590 if (count($formattedDate) == 3) {
591 $year = (int) $formattedDate[0];
592 $month = (int) $formattedDate[1];
593 $day = (int) $formattedDate[2];
595 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
603 if ($dateType == 2 ||
$dateType == 4) {
604 $formattedDate = explode("/", $value);
605 if (count($formattedDate) != 3) {
606 $formattedDate = explode("-", $value);
608 if (count($formattedDate) == 3) {
609 $year = (int) $formattedDate[2];
610 $month = (int) $formattedDate[0];
611 $day = (int) $formattedDate[1];
617 if ($dateType == 8) {
618 $dateArray = explode(' ', $value);
620 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
623 $fullMonths = self
::getFullMonthNames();
624 foreach ($fullMonths as $key => $val) {
625 if (strtolower($dateArray[0]) == strtolower($val)) {
631 $abbrMonths = self
::getAbbrMonthNames();
632 foreach ($abbrMonths as $key => $val) {
633 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
639 $year = (int) $dateArray[2];
640 $day = (int) $dateArray[1];
641 $month = (int) $monthInt;
643 if ($dateType == 16) {
644 $dateArray = explode('-', $value);
645 if (count($dateArray) != 3) {
646 $dateArray = explode('/', $value);
649 if (count($dateArray) == 3) {
651 $fullMonths = self
::getFullMonthNames();
652 foreach ($fullMonths as $key => $val) {
653 if (strtolower($dateArray[1]) == strtolower($val)) {
659 $abbrMonths = self
::getAbbrMonthNames();
660 foreach ($abbrMonths as $key => $val) {
661 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
668 $monthInt = $dateArray[1];
671 $year = (int) $dateArray[2];
672 $day = (int) $dateArray[0];
673 $month = (int) $monthInt;
679 if ($dateType == 32) {
680 $formattedDate = explode("/", $value);
681 if (count($formattedDate) == 3) {
682 $year = (int) $formattedDate[2];
683 $month = (int) $formattedDate[1];
684 $day = (int) $formattedDate[0];
691 $month = ($month < 10) ?
"0" . "$month" : $month;
692 $day = ($day < 10) ?
"0" . "$day" : $day;
696 $year = substr($now['year'], 0, 2) * 100 +
$year;
697 if ($year > ($now['year'] +
5)) {
700 elseif ($year <= ($now['year'] - 95)) {
705 if ($params[$dateParam]) {
706 $params[$dateParam] = "$year$month$day";
708 // if month is invalid return as error
709 if ($month !== '00' && $month <= 12) {
716 * Translate a TTL to a concrete expiration time.
718 * @param null|int|DateInterval $ttl
719 * @param int $default
720 * The value to use if $ttl is not specified (NULL).
722 * Timestamp (seconds since epoch).
723 * @throws \CRM_Utils_Cache_InvalidArgumentException
725 public static function convertCacheTtlToExpires($ttl, $default) {
731 return time() +
$ttl;
733 elseif ($ttl instanceof DateInterval
) {
734 return date_add(new DateTime(), $ttl)->getTimestamp();
737 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
744 * @param null|int|DateInterval $ttl
745 * @param int $default
746 * The value to use if $ttl is not specified (NULL).
748 * Seconds until expiration.
749 * @throws \CRM_Utils_Cache_InvalidArgumentException
751 public static function convertCacheTtl($ttl, $default) {
755 elseif (is_int($ttl)) {
758 elseif ($ttl instanceof DateInterval
) {
759 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
762 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
767 * @param int|false|null $timeStamp
769 * @return bool|string
771 public static function currentDBDate($timeStamp = NULL) {
772 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
781 public static function overdue($date, $now = NULL) {
782 $mysqlDate = self
::isoToMysql($date);
784 $now = self
::currentDBDate();
787 $now = self
::isoToMysql($now);
790 return !(strtotime($mysqlDate) >= strtotime($now));
794 * Get customized today.
796 * This function is used for getting customized today. To get
797 * actuall today pass 'dayParams' as null. or else pass the day,
798 * month, year values as array values
799 * Example: $dayParams = array(
800 * 'day' => '25', 'month' => '10',
801 * 'year' => '2007' );
803 * @param array $dayParams of the day, month, year.
804 * Array of the day, month, year.
806 * @param string $format
807 * Expected date format( default.
808 * format is 2007-12-21 )
811 * Return the customized today's date (Y-m-d)
813 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
814 if (is_null($dayParams) ||
empty($dayParams)) {
815 $today = date($format);
818 $today = date($format, mktime(0, 0, 0,
829 * Find whether today's date lies in
832 * @param date $startDate
833 * Start date for the range.
834 * @param date $endDate
835 * End date for the range.
838 * true if today's date is in the given date range
840 public static function getRange($startDate, $endDate) {
841 $today = date("Y-m-d");
842 $mysqlStartDate = self
::isoToMysql($startDate);
843 $mysqlEndDate = self
::isoToMysql($endDate);
844 $mysqlToday = self
::isoToMysql($today);
846 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
849 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
852 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
859 * Get start date and end from
860 * the given relative term and unit
862 * @param string $relative Relative format in the format term.unit.
865 * @param string $from
867 * @param string $fromTime
868 * @param string $toTime
871 * start date, end date
873 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
875 list($term, $unit) = explode('.', $relative, 2);
876 $dateRange = self
::relativeToAbsolute($term, $unit);
877 $from = substr($dateRange['from'], 0, 8);
878 $to = substr($dateRange['to'], 0, 8);
879 // @todo fix relativeToAbsolute & add tests
880 // relativeToAbsolute returns 8 char date strings
881 // or 14 char date + time strings.
882 // We should use those. However, it turns out to be unreliable.
883 // e.g. this.week does NOT return 235959 for 'from'
884 // so our defaults are more reliable.
885 // Currently relativeToAbsolute only supports 'whole' days so that is ok
888 $from = self
::processDate($from, $fromTime);
889 $to = self
::processDate($to, $toTime);
895 * Calculate Age in Years if greater than one year else in months.
897 * @param date $birthDate
899 * @param date $targetDate
900 * Target Date. (show age on specific date)
903 * array $results contains years or months
905 public static function calculateAge($birthDate, $targetDate = NULL) {
907 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
909 $bDate = explode('-', $formatedBirthDate);
910 $birthYear = $bDate[0];
911 $birthMonth = $bDate[1];
912 $birthDay = $bDate[2];
913 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
915 $year_diff = date("Y", $targetDate) - $birthYear;
917 // don't calculate age CRM-3143
918 if ($birthYear == '1902') {
921 switch ($year_diff) {
923 $month = (12 - $birthMonth) +
date("m", $targetDate);
925 if (date("d", $targetDate) < $birthDay) {
928 $results['months'] = $month;
930 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
931 $results['months'] = $month - 1;
934 $results['years'] = $year_diff;
939 $month = date("m", $targetDate) - $birthMonth;
940 $results['months'] = $month;
944 $results['years'] = $year_diff;
945 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
954 * Calculate next payment date according to provided unit & interval
956 * @param string $unit
957 * Frequency unit like year,month, week etc.
959 * @param int $interval
960 * Frequency interval.
963 * Start date of pledge.
965 * @param bool $dontCareTime
968 * contains new date with added interval
970 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
971 if (is_array($date)) {
972 $hour = $date['H'] ??
'00';
973 $minute = $date['i'] ??
'00';
974 $second = $date['s'] ??
'00';
975 $month = $date['M'] ??
NULL;
976 $day = $date['d'] ??
NULL;
977 $year = $date['Y'] ??
NULL;
980 extract(date_parse($date));
982 $date = mktime($hour, $minute, $second, $month, $day, $year);
985 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
989 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
993 $interval = $interval * 7;
994 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
998 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1002 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1006 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1009 $date['M'] = $scheduleDate[0];
1010 $date['d'] = $scheduleDate[1];
1011 $date['Y'] = $scheduleDate[2];
1012 if ($dontCareTime == FALSE) {
1013 $date['H'] = $scheduleDate[3];
1014 $date['i'] = $scheduleDate[4];
1015 $date['s'] = $scheduleDate[5];
1021 * Get the smarty view presentation mapping for the given format.
1023 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1024 * they should be rendered using a longer date format. This is likely as much to
1025 * do with the earlier date widget being unable to handle some formats as usablity.
1026 * However, we continue to respect this.
1029 * Given format ( eg 'M Y', 'Y M' ).
1031 * @return string|null
1032 * Smarty translation of the date format. Null is also valid and is translated
1033 * according to the available parts at the smarty layer.
1035 public static function getDateFieldViewFormat($format) {
1036 $supportableFormats = [
1037 'mm/dd' => '%B %E%f',
1038 'dd-mm' => '%E%f %B',
1042 'dd/mm/yy' => '%E%f %B %Y',
1045 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1049 * Pick the smarty format from settings that best matches the time string we have.
1051 * For view purposes we historically use the setting that most closely matches the data
1052 * in the format from our settings, as opposed to the setting configured for the field.
1057 public static function pickBestSmartyFormat($format) {
1058 if (stristr($format, 'h')) {
1059 return Civi
::settings()->get('dateformatDatetime');
1061 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1062 return Civi
::settings()->get('dateformatFull');
1064 if (stristr($format, 'm')) {
1065 return Civi
::settings()->get('dateformatPartial');
1067 return Civi
::settings()->get('dateformatYear');
1071 * Map date plugin and actual format that is used by PHP.
1075 public static function datePluginToPHPFormats() {
1076 $dateInputFormats = [
1077 "mm/dd/yy" => 'm/d/Y',
1078 "dd/mm/yy" => 'd/m/Y',
1079 "yy-mm-dd" => 'Y-m-d',
1080 "dd-mm-yy" => 'd-m-Y',
1081 "dd.mm.yy" => 'd.m.Y',
1083 "M d, yy" => 'M j, Y',
1084 "d M yy" => 'j M Y',
1085 "MM d, yy" => 'F j, Y',
1086 "d MM yy" => 'j F Y',
1087 "DD, d MM yy" => 'l, j F Y',
1095 return $dateInputFormats;
1099 * Resolves the given relative time interval into finite time limits.
1101 * @param string $relativeTerm
1102 * Relative time frame: this, previous, previous_1.
1104 * Frequency unit like year, month, week etc.
1107 * start date and end date for the relative time frame
1109 public static function relativeToAbsolute($relativeTerm, $unit) {
1111 $from = $to = $dateRange = [];
1112 $from['H'] = $from['i'] = $from['s'] = 0;
1113 $relativeTermParts = explode('_', $relativeTerm);
1114 $relativeTermPrefix = $relativeTermParts[0];
1115 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1119 switch ($relativeTerm) {
1121 $from['M'] = $from['d'] = 1;
1124 $to['Y'] = $from['Y'] = $now['year'] - 1;
1127 case 'previous_before':
1128 $from['M'] = $from['d'] = 1;
1131 $to['Y'] = $from['Y'] = $now['year'] - 2;
1135 $from['M'] = $from['d'] = 1;
1138 $from['Y'] = $now['year'] - 2;
1139 $to['Y'] = $now['year'] - 1;
1145 $to['Y'] = $now['year'] - 1;
1150 $from['M'] = $from['d'] = 1;
1151 $from['Y'] = $now['year'];
1155 case 'greater_previous':
1158 $from['Y'] = $now['year'] - 1;
1163 $to['d'] = $now['mday'];
1164 $to['M'] = $now['mon'];
1165 $to['Y'] = $now['year'];
1167 $to['i'] = $to['s'] = 59;
1168 $from = self
::intervalAdd('year', -1, $to);
1169 $from = self
::intervalAdd('second', 1, $from);
1173 $from['M'] = $from['d'] = 1;
1174 $from['Y'] = $now['year'];
1176 $to['i'] = $to['s'] = 59;
1177 $to['d'] = $now['mday'];
1178 $to['M'] = $now['mon'];
1179 $to['Y'] = $now['year'];
1183 $to['d'] = $now['mday'];
1184 $to['M'] = $now['mon'];
1185 $to['Y'] = $now['year'];
1187 $to['i'] = $to['s'] = 59;
1188 $from = self
::intervalAdd('year', -2, $to);
1189 $from = self
::intervalAdd('second', 1, $from);
1193 $to['d'] = $now['mday'];
1194 $to['M'] = $now['mon'];
1195 $to['Y'] = $now['year'];
1197 $to['i'] = $to['s'] = 59;
1198 $from = self
::intervalAdd('year', -3, $to);
1199 $from = self
::intervalAdd('second', 1, $from);
1205 $to['Y'] = $now['year'];
1210 $from['M'] = $from['d'] = 1;
1213 $to['Y'] = $from['Y'] = $now['year'] +
1;
1217 $from['d'] = $now['mday'];
1218 $from['M'] = $now['mon'];
1219 $from['Y'] = $now['year'];
1220 $to['d'] = $now['mday'] - 1;
1221 $to['M'] = $now['mon'];
1222 $to['Y'] = $now['year'] +
1;
1226 switch ($relativeTermPrefix) {
1229 $to['d'] = $now['mday'];
1230 $to['M'] = $now['mon'];
1231 $to['Y'] = $now['year'];
1233 $to['i'] = $to['s'] = 59;
1234 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1235 $from = self
::intervalAdd('second', 1, $from);
1239 $from['d'] = $from['M'] = 1;
1242 $to['Y'] = $from['Y'] = $now['year'];
1243 if (is_numeric($relativeTermSuffix)) {
1244 $from['Y'] -= ($relativeTermSuffix - 1);
1253 $config = CRM_Core_Config
::singleton();
1254 $from['d'] = $config->fiscalYearStart
['d'];
1255 $from['M'] = $config->fiscalYearStart
['M'];
1256 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1257 switch ($relativeTermPrefix) {
1259 $from['Y'] = $fYear;
1260 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1261 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1262 $to['d'] = $fiscalEnd['2'];
1263 $to['M'] = $fiscalEnd['1'];
1264 $to['Y'] = $fiscalEnd['0'];
1266 $to['i'] = $to['s'] = 59;
1267 if (is_numeric($relativeTermSuffix)) {
1268 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1269 $from = self
::intervalAdd('second', 1, $from);
1274 if (!is_numeric($relativeTermSuffix)) {
1275 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1276 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1277 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1278 $to['d'] = $fiscalEnd['2'];
1279 $to['M'] = $fiscalEnd['1'];
1280 $to['Y'] = $fiscalEnd['0'];
1282 $to['i'] = $to['s'] = 59;
1285 $from['Y'] = $fYear - $relativeTermSuffix;
1286 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1287 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1288 $to['d'] = $fiscalEnd['2'];
1289 $to['M'] = $fiscalEnd['1'];
1292 $to['i'] = $to['s'] = 59;
1297 $from['Y'] = $fYear +
1;
1298 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1299 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1300 $to['d'] = $fiscalEnd['2'];
1301 $to['M'] = $fiscalEnd['1'];
1302 $to['Y'] = $fiscalEnd['0'];
1308 switch ($relativeTerm) {
1311 $quarter = ceil($now['mon'] / 3);
1313 $from['M'] = (3 * $quarter) - 2;
1314 $to['M'] = 3 * $quarter;
1315 $to['Y'] = $from['Y'] = $now['year'];
1316 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1321 $quarter = ceil($now['mon'] / 3);
1322 $quarter = $quarter - $difference;
1324 if ($quarter <= 0) {
1329 $from['M'] = (3 * $quarter) - 2;
1330 $to['M'] = 3 * $quarter;
1331 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1332 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1335 case 'previous_before':
1337 $quarter = ceil($now['mon'] / 3);
1338 $quarter = $quarter - $difference;
1340 if ($quarter <= 0) {
1345 $from['M'] = (3 * $quarter) - 2;
1346 $to['M'] = 3 * $quarter;
1347 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1348 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1353 $quarter = ceil($now['mon'] / 3);
1354 $current_quarter = $quarter;
1355 $quarter = $quarter - $difference;
1357 if ($quarter <= 0) {
1362 $from['M'] = (3 * $quarter) - 2;
1363 switch ($current_quarter) {
1365 $to['M'] = (4 * $quarter);
1369 $to['M'] = (4 * $quarter) +
3;
1373 $to['M'] = (4 * $quarter) +
2;
1377 $to['M'] = (4 * $quarter) +
1;
1380 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1381 if ($to['M'] > 12) {
1382 $to['M'] = 3 * ($quarter - 3);
1383 $to['Y'] = $now['year'];
1385 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1389 $quarter = ceil($now['mon'] / 3) - 1;
1391 if ($quarter <= 0) {
1395 $to['M'] = 3 * $quarter;
1396 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1397 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1402 $quarter = ceil($now['mon'] / 3);
1404 $from['M'] = (3 * $quarter) - 2;
1405 $from['Y'] = $now['year'];
1409 case 'greater_previous':
1410 $quarter = ceil($now['mon'] / 3) - 1;
1412 if ($quarter <= 0) {
1416 $from['M'] = 3 * $quarter;
1417 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1418 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1423 $to['d'] = $now['mday'];
1424 $to['M'] = $now['mon'];
1425 $to['Y'] = $now['year'];
1427 $to['i'] = $to['s'] = 59;
1428 $from = self
::intervalAdd('day', -90, $to);
1429 $from = self
::intervalAdd('second', 1, $from);
1433 $quarter = ceil($now['mon'] / 3);
1435 $from['M'] = (3 * $quarter) - 2;
1436 $from['Y'] = $now['year'];
1437 $to['d'] = $now['mday'];
1438 $to['M'] = $now['mon'];
1439 $to['Y'] = $now['year'];
1441 $to['i'] = $to['s'] = 59;
1445 $quarter = ceil($now['mon'] / 3);
1446 $to['M'] = 3 * $quarter;
1447 $to['Y'] = $now['year'];
1448 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1455 $quarter = ceil($now['mon'] / 3);
1456 $quarter = $quarter - $difference;
1459 $now['year'] = $now['year'] +
1;
1462 if ($quarter <= 0) {
1467 $from['M'] = (3 * $quarter) - 2;
1468 $to['M'] = 3 * $quarter;
1469 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1470 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1474 $from['d'] = $now['mday'];
1475 $from['M'] = $now['mon'];
1476 $from['Y'] = $now['year'];
1478 $from['i'] = $to['s'] = 00;
1479 $to = self
::intervalAdd('day', 90, $from);
1480 $to = self
::intervalAdd('second', -1, $to);
1484 if ($relativeTermPrefix === 'ending') {
1485 $to['d'] = $now['mday'];
1486 $to['M'] = $now['mon'];
1487 $to['Y'] = $now['year'];
1489 $to['i'] = $to['s'] = 59;
1490 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1491 $from = self
::intervalAdd('second', 1, $from);
1497 switch ($relativeTerm) {
1500 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1501 $from['M'] = $to['M'] = $now['mon'];
1502 $from['Y'] = $to['Y'] = $now['year'];
1507 if ($now['mon'] == 1) {
1508 $from['M'] = $to['M'] = 12;
1509 $from['Y'] = $to['Y'] = $now['year'] - 1;
1512 $from['M'] = $to['M'] = $now['mon'] - 1;
1513 $from['Y'] = $to['Y'] = $now['year'];
1515 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1518 case 'previous_before':
1520 if ($now['mon'] < 3) {
1521 $from['M'] = $to['M'] = 10 +
$now['mon'];
1522 $from['Y'] = $to['Y'] = $now['year'] - 1;
1525 $from['M'] = $to['M'] = $now['mon'] - 2;
1526 $from['Y'] = $to['Y'] = $now['year'];
1528 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1533 if ($now['mon'] < 3) {
1534 $from['M'] = 10 +
$now['mon'];
1535 $from['Y'] = $now['year'] - 1;
1538 $from['M'] = $now['mon'] - 2;
1539 $from['Y'] = $now['year'];
1542 if ($now['mon'] == 1) {
1544 $to['Y'] = $now['year'] - 1;
1547 $to['M'] = $now['mon'] - 1;
1548 $to['Y'] = $now['year'];
1551 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1555 // before end of past month
1556 if ($now['mon'] == 1) {
1558 $to['Y'] = $now['year'] - 1;
1561 $to['M'] = $now['mon'] - 1;
1562 $to['Y'] = $now['year'];
1565 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1571 $from['M'] = $now['mon'];
1572 $from['Y'] = $now['year'];
1576 case 'greater_previous':
1577 // from end of past month
1578 if ($now['mon'] == 1) {
1580 $from['Y'] = $now['year'] - 1;
1583 $from['M'] = $now['mon'] - 1;
1584 $from['Y'] = $now['year'];
1587 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1592 $to['d'] = $now['mday'];
1593 $to['M'] = $now['mon'];
1594 $to['Y'] = $now['year'];
1596 $to['i'] = $to['s'] = 59;
1597 $from = self
::intervalAdd('day', -60, $to);
1598 $from = self
::intervalAdd('second', 1, $from);
1602 $to['d'] = $now['mday'];
1603 $to['M'] = $now['mon'];
1604 $to['Y'] = $now['year'];
1606 $to['i'] = $to['s'] = 59;
1607 $from = self
::intervalAdd('day', -30, $to);
1608 $from = self
::intervalAdd('second', 1, $from);
1613 $from['M'] = $now['mon'];
1614 $from['Y'] = $now['year'];
1615 $to['d'] = $now['mday'];
1616 $to['M'] = $now['mon'];
1617 $to['Y'] = $now['year'];
1619 $to['i'] = $to['s'] = 59;
1624 $to['Y'] = $now['year'];
1625 $to['M'] = $now['mon'];
1626 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1632 if ($now['mon'] == 12) {
1633 $from['M'] = $to['M'] = 1;
1634 $from['Y'] = $to['Y'] = $now['year'] +
1;
1637 $from['M'] = $to['M'] = $now['mon'] +
1;
1638 $from['Y'] = $to['Y'] = $now['year'];
1640 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1644 $from['d'] = $now['mday'];
1645 $from['M'] = $now['mon'];
1646 $from['Y'] = $now['year'];
1648 $from['i'] = $to['s'] = 00;
1649 $to = self
::intervalAdd('day', 30, $from);
1650 $to = self
::intervalAdd('second', -1, $to);
1654 $from['d'] = $now['mday'];
1655 $from['M'] = $now['mon'];
1656 $from['Y'] = $now['year'];
1658 $from['i'] = $to['s'] = 00;
1659 $to = self
::intervalAdd('day', 60, $from);
1660 $to = self
::intervalAdd('second', -1, $to);
1664 if ($relativeTermPrefix === 'ending') {
1665 $to['d'] = $now['mday'];
1666 $to['M'] = $now['mon'];
1667 $to['Y'] = $now['year'];
1669 $to['i'] = $to['s'] = 59;
1670 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1671 $from = self
::intervalAdd('second', 1, $from);
1677 $weekFirst = Civi
::settings()->get('weekBegins');
1678 $thisDay = $now['wday'];
1679 if ($weekFirst > $thisDay) {
1680 $diffDay = $thisDay - $weekFirst +
7;
1683 $diffDay = $thisDay - $weekFirst;
1685 switch ($relativeTerm) {
1687 $from['d'] = $now['mday'];
1688 $from['M'] = $now['mon'];
1689 $from['Y'] = $now['year'];
1690 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1691 $to = self
::intervalAdd('day', 6, $from);
1695 $from['d'] = $now['mday'];
1696 $from['M'] = $now['mon'];
1697 $from['Y'] = $now['year'];
1698 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1699 $to = self
::intervalAdd('day', 6, $from);
1702 case 'previous_before':
1703 $from['d'] = $now['mday'];
1704 $from['M'] = $now['mon'];
1705 $from['Y'] = $now['year'];
1706 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1707 $to = self
::intervalAdd('day', 6, $from);
1711 $from['d'] = $now['mday'];
1712 $from['M'] = $now['mon'];
1713 $from['Y'] = $now['year'];
1714 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1715 $to = self
::intervalAdd('day', 13, $from);
1719 $to['d'] = $now['mday'];
1720 $to['M'] = $now['mon'];
1721 $to['Y'] = $now['year'];
1722 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1727 $from['d'] = $now['mday'];
1728 $from['M'] = $now['mon'];
1729 $from['Y'] = $now['year'];
1730 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1734 case 'greater_previous':
1735 $from['d'] = $now['mday'];
1736 $from['M'] = $now['mon'];
1737 $from['Y'] = $now['year'];
1738 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1743 $to['d'] = $now['mday'];
1744 $to['M'] = $now['mon'];
1745 $to['Y'] = $now['year'];
1747 $to['i'] = $to['s'] = 59;
1748 $from = self
::intervalAdd('day', -7, $to);
1749 $from = self
::intervalAdd('second', 1, $from);
1753 $from['d'] = $now['mday'];
1754 $from['M'] = $now['mon'];
1755 $from['Y'] = $now['year'];
1756 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1757 $to['d'] = $now['mday'];
1758 $to['M'] = $now['mon'];
1759 $to['Y'] = $now['year'];
1761 $to['i'] = $to['s'] = 59;
1765 $to['d'] = $now['mday'];
1766 $to['M'] = $now['mon'];
1767 $to['Y'] = $now['year'];
1769 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1774 $from['d'] = $now['mday'];
1775 $from['M'] = $now['mon'];
1776 $from['Y'] = $now['year'];
1777 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1778 $to = self
::intervalAdd('day', 6, $from);
1782 $from['d'] = $now['mday'];
1783 $from['M'] = $now['mon'];
1784 $from['Y'] = $now['year'];
1786 $from['i'] = $to['s'] = 00;
1787 $to = self
::intervalAdd('day', 7, $from);
1788 $to = self
::intervalAdd('second', -1, $to);
1792 if ($relativeTermPrefix === 'ending') {
1793 $to['d'] = $now['mday'];
1794 $to['M'] = $now['mon'];
1795 $to['Y'] = $now['year'];
1797 $to['i'] = $to['s'] = 59;
1798 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1799 $from = self
::intervalAdd('second', 1, $from);
1805 switch ($relativeTerm) {
1807 $from['d'] = $to['d'] = $now['mday'];
1808 $from['M'] = $to['M'] = $now['mon'];
1809 $from['Y'] = $to['Y'] = $now['year'];
1813 $from['d'] = $now['mday'];
1814 $from['M'] = $now['mon'];
1815 $from['Y'] = $now['year'];
1816 $from = self
::intervalAdd('day', -1, $from);
1817 $to['d'] = $from['d'];
1818 $to['M'] = $from['M'];
1819 $to['Y'] = $from['Y'];
1822 case 'previous_before':
1823 $from['d'] = $now['mday'];
1824 $from['M'] = $now['mon'];
1825 $from['Y'] = $now['year'];
1826 $from = self
::intervalAdd('day', -2, $from);
1827 $to['d'] = $from['d'];
1828 $to['M'] = $from['M'];
1829 $to['Y'] = $from['Y'];
1833 $from['d'] = $to['d'] = $now['mday'];
1834 $from['M'] = $to['M'] = $now['mon'];
1835 $from['Y'] = $to['Y'] = $now['year'];
1836 $from = self
::intervalAdd('day', -2, $from);
1837 $to = self
::intervalAdd('day', -1, $to);
1841 $to['d'] = $now['mday'];
1842 $to['M'] = $now['mon'];
1843 $to['Y'] = $now['year'];
1844 $to = self
::intervalAdd('day', -1, $to);
1849 $from['d'] = $now['mday'];
1850 $from['M'] = $now['mon'];
1851 $from['Y'] = $now['year'];
1856 $to['d'] = $now['mday'];
1857 $to['M'] = $now['mon'];
1858 $to['Y'] = $now['year'];
1859 $to = self
::intervalAdd('day', 1, $to);
1860 $from['d'] = $to['d'];
1861 $from['M'] = $to['M'];
1862 $from['Y'] = $to['Y'];
1866 if ($relativeTermPrefix === 'ending') {
1867 $to['d'] = $now['mday'];
1868 $to['M'] = $now['mon'];
1869 $to['Y'] = $now['year'];
1871 $to['i'] = $to['s'] = 59;
1872 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1873 $from = self
::intervalAdd('second', 1, $from);
1879 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1880 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1885 * Calculate current fiscal year based on the fiscal month and day.
1887 * @param int $fyDate
1888 * Fiscal start date.
1890 * @param int $fyMonth
1891 * Fiscal Start Month.
1894 * $fy Current Fiscal Year
1896 public static function calculateFiscalYear($fyDate, $fyMonth) {
1897 $date = date("Y-m-d");
1898 $currentYear = date("Y");
1900 // recalculate the date because month 4::04 make the difference
1901 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1902 $fyDate = $fiscalYear[2];
1903 $fyMonth = $fiscalYear[1];
1904 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1906 if ($fyStartDate > $date) {
1907 $fy = intval(intval($currentYear) - 1);
1910 $fy = intval($currentYear);
1916 * Function to process date, convert to mysql format
1918 * @param string $date
1920 * @param string $time
1922 * @param bool|string $returnNullString 'null' needs to be returned
1923 * so that db oject will set null in db
1924 * @param string $format
1925 * Expected return date format.( default is mysql ).
1928 * date format that is excepted by mysql
1930 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1933 if ($returnNullString) {
1934 $mysqlDate = 'null';
1938 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1945 * Add the metadata about a date field to the field.
1947 * This metadata will work with the call $form->add('datepicker', ...
1949 * @param array $fieldMetaData
1950 * @param array $field
1954 public static function addDateMetadataToField($fieldMetaData, $field) {
1955 if (isset($fieldMetaData['html'])) {
1956 $field['html_type'] = $fieldMetaData['html']['type'];
1957 if ($field['html_type'] === 'Select Date') {
1958 if (!isset($field['date_format'])) {
1959 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1960 $field['start_date_years'] = $dateAttributes['minYear'];
1961 $field['end_date_years'] = $dateAttributes['maxYear'];
1962 $field['date_format'] = $dateAttributes['format'];
1963 $field['is_datetime_field'] = TRUE;
1964 $field['time_format'] = $dateAttributes['time'];
1965 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1967 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1968 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1975 * Get the fields required for the 'extra' parameter when adding a datepicker.
1977 * @param array $field
1981 public static function getDatePickerExtra($field) {
1983 if (isset($field['date_format'])) {
1984 $extra['date'] = $field['date_format'];
1985 $extra['time'] = $field['time_format'];
1987 $thisYear = date('Y');
1988 if (isset($field['start_date_years'])) {
1989 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1991 if (isset($field['end_date_years'])) {
1992 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1998 * Get the attributes parameters required for datepicker.
2000 * @param array $field
2004 * Array ready to pass to $this->addForm('datepicker' as attributes.
2006 public static function getDatePickerAttributes(&$field) {
2009 'start_date_years' => 'minYear',
2010 'end_date_years' => 'maxYear',
2011 'date_format' => 'format',
2013 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2014 if (isset($field[$dateAttribute])) {
2015 $attributes[$mapTo] = $field[$dateAttribute];
2022 * Function to convert mysql to date plugin format.
2024 * @param string $mysqlDate
2027 * @param null $formatType
2028 * @param null $format
2029 * @param null $timeFormat
2034 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2035 // if date is not passed assume it as today
2037 $mysqlDate = date('Y-m-d G:i:s');
2040 $config = CRM_Core_Config
::singleton();
2042 // get actual format
2043 $params = ['name' => $formatType];
2045 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2047 if ($values['date_format']) {
2048 $format = $values['date_format'];
2051 if (isset($values['time_format'])) {
2052 $timeFormat = $values['time_format'];
2056 $dateFormat = 'm/d/Y';
2057 $date = date($dateFormat, strtotime($mysqlDate));
2060 $timeFormat = $config->timeInputFormat
;
2063 $actualTimeFormat = "g:iA";
2064 $appendZeroLength = 7;
2065 if ($timeFormat > 1) {
2066 $actualTimeFormat = "G:i";
2067 $appendZeroLength = 5;
2070 $time = date($actualTimeFormat, strtotime($mysqlDate));
2072 // need to append zero for hours < 10
2073 if (strlen($time) < $appendZeroLength) {
2074 $time = '0' . $time;
2077 return [$date, $time];
2081 * Function get date format.
2083 * @param string $formatType
2084 * Date name e.g. birth.
2088 public static function getDateFormat($formatType = NULL) {
2091 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2092 $formatType, 'date_format', 'name'
2097 $config = CRM_Core_Config
::singleton();
2098 $format = $config->dateInputFormat
;
2107 * @return null|string
2109 public static function formatDate($date, $dateType) {
2110 $formattedDate = NULL;
2112 return $formattedDate;
2115 // 1. first convert date to default format.
2116 // 2. append time to default formatted date (might be removed during format)
2117 // 3. validate date / date time.
2118 // 4. If date and time then convert to default date time format.
2121 $dateParams = [$dateKey => $date];
2123 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2124 $dateVal = $dateParams[$dateKey];
2126 if ($dateType == 1) {
2128 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2129 $ruleName = 'dateTime';
2130 if (strpos($date, '-') !== FALSE) {
2131 $dateVal .= array_shift($matches);
2137 $valid = CRM_Utils_Rule
::$ruleName($dateVal);
2140 // format date and time to default.
2141 if ($ruleName == 'dateTime') {
2142 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2143 // hack to add seconds
2146 $formattedDate = $dateVal;
2150 return $formattedDate;
2154 * Function to return days of the month.
2158 public static function getCalendarDayOfMonth() {
2160 for ($i = 1; $i <= 31; $i++
) {
2163 $month[$i] = $i . ' / Last day of month';
2170 * Convert a relative date format to an api field.
2172 * @param array $params
2173 * @param string $dateField
2174 * @param bool $isDatePicker
2175 * Non datepicker fields are deprecated. Exterminate Exterminate.
2176 * (but for now handle them).
2178 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2179 if (!empty($params[$dateField . '_relative'])) {
2180 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2181 unset($params[$dateField . '_relative']);
2183 if (!empty($params[$dateField . '_low'])) {
2184 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2185 unset($params[$dateField . '_low']);
2187 if (!empty($params[$dateField . '_high'])) {
2188 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2189 unset($params[$dateField . '_high']);
2191 if (empty($dates)) {
2194 if (empty($dates[0])) {
2195 $params[$dateField] = ['<=' => $dates[1]];
2197 elseif (empty($dates[1])) {
2198 $params[$dateField] = ['>=' => $dates[0]];
2201 $params[$dateField] = ['BETWEEN' => $dates];
2206 * Print out a date object in specified format in local timezone
2208 * @param DateTimeObject $dateObject
2209 * @param string $format
2212 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2213 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2214 $dateObject->setTimezone($systemTimeZone);
2215 return $dateObject->format($format);