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() {
165 // First day of the week
166 $firstDay = Civi
::settings()->get('weekBegins');
168 // set LC_TIME and build the arrays from locale-provided names
169 // June 1st, 1970 was a Monday
170 CRM_Core_I18n
::setLcTime();
171 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
172 $days[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
179 * Return full weekday names according to the locale.
181 * Array will be in localized order according to 'weekBegins' setting,
182 * but array keys will always match to:
188 * 0-based array with full weekday names
191 public static function getFullWeekdayNames() {
194 // First day of the week
195 $firstDay = Civi
::settings()->get('weekBegins');
197 // set LC_TIME and build the arrays from locale-provided names
198 // June 1st, 1970 was a Monday
199 CRM_Core_I18n
::setLcTime();
200 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
201 $days[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
208 * Return abbreviated month names according to the locale.
213 * 1-based array with abbreviated month names
216 public static function &getAbbrMonthNames($month = FALSE) {
217 static $abbrMonthNames;
218 if (!isset($abbrMonthNames)) {
220 // set LC_TIME and build the arrays from locale-provided names
221 CRM_Core_I18n
::setLcTime();
222 for ($i = 1; $i <= 12; $i++
) {
223 $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
227 return $abbrMonthNames[$month];
229 return $abbrMonthNames;
233 * Return full month names according to the locale.
236 * 1-based array with full month names
239 public static function &getFullMonthNames() {
240 static $fullMonthNames;
241 if (!isset($fullMonthNames)) {
243 // set LC_TIME and build the arrays from locale-provided names
244 CRM_Core_I18n
::setLcTime();
245 for ($i = 1; $i <= 12; $i++
) {
246 $fullMonthNames[$i] = strftime('%B', mktime(0, 0, 0, $i, 10, 1970));
249 return $fullMonthNames;
257 public static function unixTime($string) {
258 if (empty($string)) {
261 $parsedDate = date_parse($string);
262 return mktime(CRM_Utils_Array
::value('hour', $parsedDate),
263 CRM_Utils_Array
::value('minute', $parsedDate),
265 CRM_Utils_Array
::value('month', $parsedDate),
266 CRM_Utils_Array
::value('day', $parsedDate),
267 CRM_Utils_Array
::value('year', $parsedDate)
272 * Create a date and time string in a provided format.
274 * %b - abbreviated month name ('Jan'..'Dec')
275 * %B - full month name ('January'..'December')
276 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
277 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
278 * %E - day of the month as a decimal number ('1'..'31')
279 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
280 * %H - hour in 24-hour format, 0-padded ('00'..'23')
281 * %I - hour in 12-hour format, 0-padded ('01'..'12')
282 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
283 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
284 * %m - month as a decimal number, 0-padded ('01'..'12')
285 * %M - minute, 0-padded ('00'..'60')
286 * %p - lowercase ante/post meridiem ('am', 'pm')
287 * %P - uppercase ante/post meridiem ('AM', 'PM')
288 * %Y - year as a decimal number including the century ('2005')
290 * @param string $dateString
291 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
292 * @param string $format
294 * @param array $dateParts
295 * An array with the desired date parts.
298 * the $format-formatted $date
300 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
301 // 1-based (January) month names arrays
302 $abbrMonths = self
::getAbbrMonthNames();
303 $fullMonths = self
::getFullMonthNames();
306 $config = CRM_Core_Config
::singleton();
309 if (array_intersect(['h', 'H'], $dateParts)) {
310 $format = $config->dateformatDatetime
;
312 elseif (array_intersect(['d', 'j'], $dateParts)) {
313 $format = $config->dateformatFull
;
315 elseif (array_intersect(['m', 'M'], $dateParts)) {
316 $format = $config->dateformatPartial
;
319 $format = $config->dateformatYear
;
323 if (strpos($dateString, '-')) {
324 $month = (int) substr($dateString, 5, 2);
325 $day = (int) substr($dateString, 8, 2);
328 $month = (int) substr($dateString, 4, 2);
329 $day = (int) substr($dateString, 6, 2);
332 if (strlen($dateString) > 10) {
333 $format = $config->dateformatDatetime
;
336 $format = $config->dateformatFull
;
338 elseif ($month > 0) {
339 $format = $config->dateformatPartial
;
342 $format = $config->dateformatYear
;
347 if (!CRM_Utils_System
::isNull($dateString)) {
348 if (strpos($dateString, '-')) {
349 $year = (int) substr($dateString, 0, 4);
350 $month = (int) substr($dateString, 5, 2);
351 $day = (int) substr($dateString, 8, 2);
353 $hour24 = (int) substr($dateString, 11, 2);
354 $minute = (int) substr($dateString, 14, 2);
357 $year = (int) substr($dateString, 0, 4);
358 $month = (int) substr($dateString, 4, 2);
359 $day = (int) substr($dateString, 6, 2);
361 $hour24 = (int) substr($dateString, 8, 2);
362 $minute = (int) substr($dateString, 10, 2);
365 if ($day %
10 == 1 and $day != 11) {
368 elseif ($day %
10 == 2 and $day != 12) {
371 elseif ($day %
10 == 3 and $day != 13) {
392 $hour12 = $hour24 - 12;
398 '%b' => $abbrMonths[$month] ??
NULL,
399 '%B' => $fullMonths[$month] ??
NULL,
400 '%d' => $day > 9 ?
$day : '0' . $day,
401 '%e' => $day > 9 ?
$day : ' ' . $day,
404 '%H' => $hour24 > 9 ?
$hour24 : '0' . $hour24,
405 '%h' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
406 '%I' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
407 '%k' => $hour24 > 9 ?
$hour24 : ' ' . $hour24,
408 '%l' => $hour12 > 9 ?
$hour12 : ' ' . $hour12,
409 '%m' => $month > 9 ?
$month : '0' . $month,
410 '%M' => $minute > 9 ?
$minute : '0' . $minute,
411 '%i' => $minute > 9 ?
$minute : '0' . $minute,
412 '%p' => strtolower($type),
418 return strtr($format, $date);
426 * Format the field according to the site's preferred date format.
428 * This is likely to look something like December 31st, 2020.
430 * @param string $date
434 public static function formatDateOnlyLong(string $date):string {
435 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
439 * Wrapper for customFormat that takes a timestamp
441 * @param int $timestamp
442 * Date and time in timestamp format.
443 * @param string $format
445 * @param array $dateParts
446 * An array with the desired date parts.
449 * the $format-formatted $date
451 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
452 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
456 * Converts the date/datetime from MySQL format to ISO format
458 * @param string $mysql
459 * Date/datetime in MySQL format.
462 * date/datetime in ISO format
464 public static function mysqlToIso($mysql) {
465 $year = substr($mysql, 0, 4);
466 $month = substr($mysql, 4, 2);
467 $day = substr($mysql, 6, 2);
468 $hour = substr($mysql, 8, 2);
469 $minute = substr($mysql, 10, 2);
470 $second = substr($mysql, 12, 2);
496 * Converts the date/datetime from ISO format to MySQL format
497 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
498 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
499 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
502 * Date/datetime in ISO format.
505 * date/datetime in MySQL format
507 public static function isoToMysql($iso) {
508 $dropArray = ['-' => '', ':' => '', ' ' => ''];
509 return strtr($iso, $dropArray);
513 * Converts the any given date to default date format.
515 * @param array $params
516 * Has given date-format.
517 * @param int $dateType
519 * @param string $dateParam
524 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
526 $cen = substr($now['year'], 0, 2);
530 if (!empty($params[$dateParam])) {
531 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
532 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
537 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
543 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
549 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
555 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
561 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
567 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
573 if ($dateType == 1) {
574 $formattedDate = explode("-", $value);
575 if (count($formattedDate) == 3) {
576 $year = (int) $formattedDate[0];
577 $month = (int) $formattedDate[1];
578 $day = (int) $formattedDate[2];
580 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
588 if ($dateType == 2 ||
$dateType == 4) {
589 $formattedDate = explode("/", $value);
590 if (count($formattedDate) != 3) {
591 $formattedDate = explode("-", $value);
593 if (count($formattedDate) == 3) {
594 $year = (int) $formattedDate[2];
595 $month = (int) $formattedDate[0];
596 $day = (int) $formattedDate[1];
602 if ($dateType == 8) {
603 $dateArray = explode(' ', $value);
605 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
608 $fullMonths = self
::getFullMonthNames();
609 foreach ($fullMonths as $key => $val) {
610 if (strtolower($dateArray[0]) == strtolower($val)) {
616 $abbrMonths = self
::getAbbrMonthNames();
617 foreach ($abbrMonths as $key => $val) {
618 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
624 $year = (int) $dateArray[2];
625 $day = (int) $dateArray[1];
626 $month = (int) $monthInt;
628 if ($dateType == 16) {
629 $dateArray = explode('-', $value);
630 if (count($dateArray) != 3) {
631 $dateArray = explode('/', $value);
634 if (count($dateArray) == 3) {
636 $fullMonths = self
::getFullMonthNames();
637 foreach ($fullMonths as $key => $val) {
638 if (strtolower($dateArray[1]) == strtolower($val)) {
644 $abbrMonths = self
::getAbbrMonthNames();
645 foreach ($abbrMonths as $key => $val) {
646 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
653 $monthInt = $dateArray[1];
656 $year = (int) $dateArray[2];
657 $day = (int) $dateArray[0];
658 $month = (int) $monthInt;
664 if ($dateType == 32) {
665 $formattedDate = explode("/", $value);
666 if (count($formattedDate) == 3) {
667 $year = (int) $formattedDate[2];
668 $month = (int) $formattedDate[1];
669 $day = (int) $formattedDate[0];
676 $month = ($month < 10) ?
"0" . "$month" : $month;
677 $day = ($day < 10) ?
"0" . "$day" : $day;
679 $year = (int ) $year;
680 // simple heuristic to determine what century to use
681 // 00 - 20 is always 2000 - 2020
682 // 21 - 99 is always 1921 - 1999
684 $year = (strlen($year) == 1) ?
$cen . '0' . $year : $cen . $year;
686 elseif ($year < 100) {
687 $year = $prevCen . $year;
690 if ($params[$dateParam]) {
691 $params[$dateParam] = "$year$month$day";
693 // if month is invalid return as error
694 if ($month !== '00' && $month <= 12) {
705 public static function isDate(&$date) {
706 if (CRM_Utils_System
::isNull($date)) {
713 * Translate a TTL to a concrete expiration time.
715 * @param NULL|int|DateInterval $ttl
716 * @param int $default
717 * The value to use if $ttl is not specified (NULL).
719 * Timestamp (seconds since epoch).
720 * @throws \CRM_Utils_Cache_InvalidArgumentException
722 public static function convertCacheTtlToExpires($ttl, $default) {
728 return time() +
$ttl;
730 elseif ($ttl instanceof DateInterval
) {
731 return date_add(new DateTime(), $ttl)->getTimestamp();
734 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
741 * @param NULL|int|DateInterval $ttl
742 * @param int $default
743 * The value to use if $ttl is not specified (NULL).
745 * Seconds until expiration.
746 * @throws \CRM_Utils_Cache_InvalidArgumentException
748 public static function convertCacheTtl($ttl, $default) {
752 elseif (is_int($ttl)) {
755 elseif ($ttl instanceof DateInterval
) {
756 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
759 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
764 * @param null $timeStamp
766 * @return bool|string
768 public static function currentDBDate($timeStamp = NULL) {
769 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
778 public static function overdue($date, $now = NULL) {
779 $mysqlDate = self
::isoToMysql($date);
781 $now = self
::currentDBDate();
784 $now = self
::isoToMysql($now);
787 return !(strtotime($mysqlDate) >= strtotime($now));
791 * Get customized today.
793 * This function is used for getting customized today. To get
794 * actuall today pass 'dayParams' as null. or else pass the day,
795 * month, year values as array values
796 * Example: $dayParams = array(
797 * 'day' => '25', 'month' => '10',
798 * 'year' => '2007' );
800 * @param array $dayParams of the day, month, year.
801 * Array of the day, month, year.
803 * @param string $format
804 * Expected date format( default.
805 * format is 2007-12-21 )
808 * Return the customized today's date (Y-m-d)
810 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
811 if (is_null($dayParams) ||
empty($dayParams)) {
812 $today = date($format);
815 $today = date($format, mktime(0, 0, 0,
826 * Find whether today's date lies in
829 * @param date $startDate
830 * Start date for the range.
831 * @param date $endDate
832 * End date for the range.
835 * true if today's date is in the given date range
837 public static function getRange($startDate, $endDate) {
838 $today = date("Y-m-d");
839 $mysqlStartDate = self
::isoToMysql($startDate);
840 $mysqlEndDate = self
::isoToMysql($endDate);
841 $mysqlToday = self
::isoToMysql($today);
843 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
846 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
849 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
856 * Get start date and end from
857 * the given relative term and unit
859 * @param string $relative Relative format in the format term.unit.
862 * @param string $from
864 * @param string $fromTime
865 * @param string $toTime
868 * start date, end date
870 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
872 list($term, $unit) = explode('.', $relative, 2);
873 $dateRange = self
::relativeToAbsolute($term, $unit);
874 $from = substr($dateRange['from'], 0, 8);
875 $to = substr($dateRange['to'], 0, 8);
876 // @todo fix relativeToAbsolute & add tests
877 // relativeToAbsolute returns 8 char date strings
878 // or 14 char date + time strings.
879 // We should use those. However, it turns out to be unreliable.
880 // e.g. this.week does NOT return 235959 for 'from'
881 // so our defaults are more reliable.
882 // Currently relativeToAbsolute only supports 'whole' days so that is ok
885 $from = self
::processDate($from, $fromTime);
886 $to = self
::processDate($to, $toTime);
892 * Calculate Age in Years if greater than one year else in months.
894 * @param date $birthDate
896 * @param date $targetDate
897 * Target Date. (show age on specific date)
900 * array $results contains years or months
902 public static function calculateAge($birthDate, $targetDate = NULL) {
904 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
906 $bDate = explode('-', $formatedBirthDate);
907 $birthYear = $bDate[0];
908 $birthMonth = $bDate[1];
909 $birthDay = $bDate[2];
910 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
912 $year_diff = date("Y", $targetDate) - $birthYear;
914 // don't calculate age CRM-3143
915 if ($birthYear == '1902') {
918 switch ($year_diff) {
920 $month = (12 - $birthMonth) +
date("m", $targetDate);
922 if (date("d", $targetDate) < $birthDay) {
925 $results['months'] = $month;
927 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
928 $results['months'] = $month - 1;
931 $results['years'] = $year_diff;
936 $month = date("m", $targetDate) - $birthMonth;
937 $results['months'] = $month;
941 $results['years'] = $year_diff;
942 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
951 * Calculate next payment date according to provided unit & interval
953 * @param string $unit
954 * Frequency unit like year,month, week etc.
956 * @param int $interval
957 * Frequency interval.
960 * Start date of pledge.
962 * @param bool $dontCareTime
965 * contains new date with added interval
967 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
968 if (is_array($date)) {
969 $hour = $date['H'] ??
'00';
970 $minute = $date['i'] ??
'00';
971 $second = $date['s'] ??
'00';
972 $month = $date['M'] ??
NULL;
973 $day = $date['d'] ??
NULL;
974 $year = $date['Y'] ??
NULL;
977 extract(date_parse($date));
979 $date = mktime($hour, $minute, $second, $month, $day, $year);
982 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
986 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
990 $interval = $interval * 7;
991 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
995 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
999 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1003 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1006 $date['M'] = $scheduleDate[0];
1007 $date['d'] = $scheduleDate[1];
1008 $date['Y'] = $scheduleDate[2];
1009 if ($dontCareTime == FALSE) {
1010 $date['H'] = $scheduleDate[3];
1011 $date['i'] = $scheduleDate[4];
1012 $date['s'] = $scheduleDate[5];
1018 * Get the smarty view presentation mapping for the given format.
1020 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1021 * they should be rendered using a longer date format. This is likely as much to
1022 * do with the earlier date widget being unable to handle some formats as usablity.
1023 * However, we continue to respect this.
1026 * Given format ( eg 'M Y', 'Y M' ).
1028 * @return string|null
1029 * Smarty translation of the date format. Null is also valid and is translated
1030 * according to the available parts at the smarty layer.
1032 public static function getDateFieldViewFormat($format) {
1033 $supportableFormats = [
1034 'mm/dd' => '%B %E%f',
1035 'dd-mm' => '%E%f %B',
1039 'dd/mm/yy' => '%E%f %B %Y',
1042 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1046 * Pick the smarty format from settings that best matches the time string we have.
1048 * For view purposes we historically use the setting that most closely matches the data
1049 * in the format from our settings, as opposed to the setting configured for the field.
1054 public static function pickBestSmartyFormat($format) {
1055 if (stristr($format, 'h')) {
1056 return Civi
::settings()->get('dateformatDatetime');
1058 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1059 return Civi
::settings()->get('dateformatFull');
1061 if (stristr($format, 'm')) {
1062 return Civi
::settings()->get('dateformatPartial');
1064 return Civi
::settings()->get('dateformatYear');
1068 * Map date plugin and actual format that is used by PHP.
1072 public static function datePluginToPHPFormats() {
1073 $dateInputFormats = [
1074 "mm/dd/yy" => 'm/d/Y',
1075 "dd/mm/yy" => 'd/m/Y',
1076 "yy-mm-dd" => 'Y-m-d',
1077 "dd-mm-yy" => 'd-m-Y',
1078 "dd.mm.yy" => 'd.m.Y',
1080 "M d, yy" => 'M j, Y',
1081 "d M yy" => 'j M Y',
1082 "MM d, yy" => 'F j, Y',
1083 "d MM yy" => 'j F Y',
1084 "DD, d MM yy" => 'l, j F Y',
1092 return $dateInputFormats;
1096 * Resolves the given relative time interval into finite time limits.
1098 * @param string $relativeTerm
1099 * Relative time frame: this, previous, previous_1.
1101 * Frequency unit like year, month, week etc.
1104 * start date and end date for the relative time frame
1106 public static function relativeToAbsolute($relativeTerm, $unit) {
1108 $from = $to = $dateRange = [];
1109 $from['H'] = $from['i'] = $from['s'] = 0;
1110 $relativeTermParts = explode('_', $relativeTerm);
1111 $relativeTermPrefix = $relativeTermParts[0];
1112 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1116 switch ($relativeTerm) {
1118 $from['M'] = $from['d'] = 1;
1121 $to['Y'] = $from['Y'] = $now['year'] - 1;
1124 case 'previous_before':
1125 $from['M'] = $from['d'] = 1;
1128 $to['Y'] = $from['Y'] = $now['year'] - 2;
1132 $from['M'] = $from['d'] = 1;
1135 $from['Y'] = $now['year'] - 2;
1136 $to['Y'] = $now['year'] - 1;
1142 $to['Y'] = $now['year'] - 1;
1147 $from['M'] = $from['d'] = 1;
1148 $from['Y'] = $now['year'];
1152 case 'greater_previous':
1155 $from['Y'] = $now['year'] - 1;
1160 $to['d'] = $now['mday'];
1161 $to['M'] = $now['mon'];
1162 $to['Y'] = $now['year'];
1164 $to['i'] = $to['s'] = 59;
1165 $from = self
::intervalAdd('year', -1, $to);
1166 $from = self
::intervalAdd('second', 1, $from);
1170 $from['M'] = $from['d'] = 1;
1171 $from['Y'] = $now['year'];
1173 $to['i'] = $to['s'] = 59;
1174 $to['d'] = $now['mday'];
1175 $to['M'] = $now['mon'];
1176 $to['Y'] = $now['year'];
1180 $to['d'] = $now['mday'];
1181 $to['M'] = $now['mon'];
1182 $to['Y'] = $now['year'];
1184 $to['i'] = $to['s'] = 59;
1185 $from = self
::intervalAdd('year', -2, $to);
1186 $from = self
::intervalAdd('second', 1, $from);
1190 $to['d'] = $now['mday'];
1191 $to['M'] = $now['mon'];
1192 $to['Y'] = $now['year'];
1194 $to['i'] = $to['s'] = 59;
1195 $from = self
::intervalAdd('year', -3, $to);
1196 $from = self
::intervalAdd('second', 1, $from);
1202 $to['Y'] = $now['year'];
1207 $from['M'] = $from['d'] = 1;
1210 $to['Y'] = $from['Y'] = $now['year'] +
1;
1214 $from['d'] = $now['mday'];
1215 $from['M'] = $now['mon'];
1216 $from['Y'] = $now['year'];
1217 $to['d'] = $now['mday'] - 1;
1218 $to['M'] = $now['mon'];
1219 $to['Y'] = $now['year'] +
1;
1223 switch ($relativeTermPrefix) {
1226 $to['d'] = $now['mday'];
1227 $to['M'] = $now['mon'];
1228 $to['Y'] = $now['year'];
1230 $to['i'] = $to['s'] = 59;
1231 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1232 $from = self
::intervalAdd('second', 1, $from);
1236 $from['d'] = $from['M'] = 1;
1239 $to['Y'] = $from['Y'] = $now['year'];
1240 if (is_numeric($relativeTermSuffix)) {
1241 $from['Y'] -= ($relativeTermSuffix - 1);
1250 $config = CRM_Core_Config
::singleton();
1251 $from['d'] = $config->fiscalYearStart
['d'];
1252 $from['M'] = $config->fiscalYearStart
['M'];
1253 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1254 switch ($relativeTermPrefix) {
1256 $from['Y'] = $fYear;
1257 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1258 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1259 $to['d'] = $fiscalEnd['2'];
1260 $to['M'] = $fiscalEnd['1'];
1261 $to['Y'] = $fiscalEnd['0'];
1263 $to['i'] = $to['s'] = 59;
1264 if (is_numeric($relativeTermSuffix)) {
1265 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1266 $from = self
::intervalAdd('second', 1, $from);
1271 if (!is_numeric($relativeTermSuffix)) {
1272 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1273 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1274 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1275 $to['d'] = $fiscalEnd['2'];
1276 $to['M'] = $fiscalEnd['1'];
1277 $to['Y'] = $fiscalEnd['0'];
1279 $to['i'] = $to['s'] = 59;
1282 $from['Y'] = $fYear - $relativeTermSuffix;
1283 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1284 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1285 $to['d'] = $fiscalEnd['2'];
1286 $to['M'] = $fiscalEnd['1'];
1289 $to['i'] = $to['s'] = 59;
1294 $from['Y'] = $fYear +
1;
1295 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1296 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1297 $to['d'] = $fiscalEnd['2'];
1298 $to['M'] = $fiscalEnd['1'];
1299 $to['Y'] = $fiscalEnd['0'];
1305 switch ($relativeTerm) {
1308 $quarter = ceil($now['mon'] / 3);
1310 $from['M'] = (3 * $quarter) - 2;
1311 $to['M'] = 3 * $quarter;
1312 $to['Y'] = $from['Y'] = $now['year'];
1313 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1318 $quarter = ceil($now['mon'] / 3);
1319 $quarter = $quarter - $difference;
1321 if ($quarter <= 0) {
1326 $from['M'] = (3 * $quarter) - 2;
1327 $to['M'] = 3 * $quarter;
1328 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1329 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1332 case 'previous_before':
1334 $quarter = ceil($now['mon'] / 3);
1335 $quarter = $quarter - $difference;
1337 if ($quarter <= 0) {
1342 $from['M'] = (3 * $quarter) - 2;
1343 $to['M'] = 3 * $quarter;
1344 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1345 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1350 $quarter = ceil($now['mon'] / 3);
1351 $current_quarter = $quarter;
1352 $quarter = $quarter - $difference;
1354 if ($quarter <= 0) {
1359 $from['M'] = (3 * $quarter) - 2;
1360 switch ($current_quarter) {
1362 $to['M'] = (4 * $quarter);
1366 $to['M'] = (4 * $quarter) +
3;
1370 $to['M'] = (4 * $quarter) +
2;
1374 $to['M'] = (4 * $quarter) +
1;
1377 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1378 if ($to['M'] > 12) {
1379 $to['M'] = 3 * ($quarter - 3);
1380 $to['Y'] = $now['year'];
1382 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1386 $quarter = ceil($now['mon'] / 3) - 1;
1388 if ($quarter <= 0) {
1392 $to['M'] = 3 * $quarter;
1393 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1394 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1399 $quarter = ceil($now['mon'] / 3);
1401 $from['M'] = (3 * $quarter) - 2;
1402 $from['Y'] = $now['year'];
1406 case 'greater_previous':
1407 $quarter = ceil($now['mon'] / 3) - 1;
1409 if ($quarter <= 0) {
1413 $from['M'] = 3 * $quarter;
1414 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1415 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1420 $to['d'] = $now['mday'];
1421 $to['M'] = $now['mon'];
1422 $to['Y'] = $now['year'];
1424 $to['i'] = $to['s'] = 59;
1425 $from = self
::intervalAdd('day', -90, $to);
1426 $from = self
::intervalAdd('second', 1, $from);
1430 $quarter = ceil($now['mon'] / 3);
1432 $from['M'] = (3 * $quarter) - 2;
1433 $from['Y'] = $now['year'];
1434 $to['d'] = $now['mday'];
1435 $to['M'] = $now['mon'];
1436 $to['Y'] = $now['year'];
1438 $to['i'] = $to['s'] = 59;
1442 $quarter = ceil($now['mon'] / 3);
1443 $to['M'] = 3 * $quarter;
1444 $to['Y'] = $now['year'];
1445 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1452 $quarter = ceil($now['mon'] / 3);
1453 $quarter = $quarter - $difference;
1456 $now['year'] = $now['year'] +
1;
1459 if ($quarter <= 0) {
1464 $from['M'] = (3 * $quarter) - 2;
1465 $to['M'] = 3 * $quarter;
1466 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1467 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1471 $from['d'] = $now['mday'];
1472 $from['M'] = $now['mon'];
1473 $from['Y'] = $now['year'];
1475 $from['i'] = $to['s'] = 00;
1476 $to = self
::intervalAdd('day', 90, $from);
1477 $to = self
::intervalAdd('second', -1, $to);
1481 if ($relativeTermPrefix === 'ending') {
1482 $to['d'] = $now['mday'];
1483 $to['M'] = $now['mon'];
1484 $to['Y'] = $now['year'];
1486 $to['i'] = $to['s'] = 59;
1487 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1488 $from = self
::intervalAdd('second', 1, $from);
1494 switch ($relativeTerm) {
1497 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1498 $from['M'] = $to['M'] = $now['mon'];
1499 $from['Y'] = $to['Y'] = $now['year'];
1504 if ($now['mon'] == 1) {
1505 $from['M'] = $to['M'] = 12;
1506 $from['Y'] = $to['Y'] = $now['year'] - 1;
1509 $from['M'] = $to['M'] = $now['mon'] - 1;
1510 $from['Y'] = $to['Y'] = $now['year'];
1512 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1515 case 'previous_before':
1517 if ($now['mon'] < 3) {
1518 $from['M'] = $to['M'] = 10 +
$now['mon'];
1519 $from['Y'] = $to['Y'] = $now['year'] - 1;
1522 $from['M'] = $to['M'] = $now['mon'] - 2;
1523 $from['Y'] = $to['Y'] = $now['year'];
1525 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1530 if ($now['mon'] < 3) {
1531 $from['M'] = 10 +
$now['mon'];
1532 $from['Y'] = $now['year'] - 1;
1535 $from['M'] = $now['mon'] - 2;
1536 $from['Y'] = $now['year'];
1539 if ($now['mon'] == 1) {
1541 $to['Y'] = $now['year'] - 1;
1544 $to['M'] = $now['mon'] - 1;
1545 $to['Y'] = $now['year'];
1548 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1552 // before end of past month
1553 if ($now['mon'] == 1) {
1555 $to['Y'] = $now['year'] - 1;
1558 $to['M'] = $now['mon'] - 1;
1559 $to['Y'] = $now['year'];
1562 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1568 $from['M'] = $now['mon'];
1569 $from['Y'] = $now['year'];
1573 case 'greater_previous':
1574 // from end of past month
1575 if ($now['mon'] == 1) {
1577 $from['Y'] = $now['year'] - 1;
1580 $from['M'] = $now['mon'] - 1;
1581 $from['Y'] = $now['year'];
1584 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1589 $to['d'] = $now['mday'];
1590 $to['M'] = $now['mon'];
1591 $to['Y'] = $now['year'];
1593 $to['i'] = $to['s'] = 59;
1594 $from = self
::intervalAdd('day', -60, $to);
1595 $from = self
::intervalAdd('second', 1, $from);
1599 $to['d'] = $now['mday'];
1600 $to['M'] = $now['mon'];
1601 $to['Y'] = $now['year'];
1603 $to['i'] = $to['s'] = 59;
1604 $from = self
::intervalAdd('day', -30, $to);
1605 $from = self
::intervalAdd('second', 1, $from);
1610 $from['M'] = $now['mon'];
1611 $from['Y'] = $now['year'];
1612 $to['d'] = $now['mday'];
1613 $to['M'] = $now['mon'];
1614 $to['Y'] = $now['year'];
1616 $to['i'] = $to['s'] = 59;
1621 $to['Y'] = $now['year'];
1622 $to['M'] = $now['mon'];
1623 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1629 if ($now['mon'] == 12) {
1630 $from['M'] = $to['M'] = 1;
1631 $from['Y'] = $to['Y'] = $now['year'] +
1;
1634 $from['M'] = $to['M'] = $now['mon'] +
1;
1635 $from['Y'] = $to['Y'] = $now['year'];
1637 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1641 $from['d'] = $now['mday'];
1642 $from['M'] = $now['mon'];
1643 $from['Y'] = $now['year'];
1645 $from['i'] = $to['s'] = 00;
1646 $to = self
::intervalAdd('day', 30, $from);
1647 $to = self
::intervalAdd('second', -1, $to);
1651 $from['d'] = $now['mday'];
1652 $from['M'] = $now['mon'];
1653 $from['Y'] = $now['year'];
1655 $from['i'] = $to['s'] = 00;
1656 $to = self
::intervalAdd('day', 60, $from);
1657 $to = self
::intervalAdd('second', -1, $to);
1661 if ($relativeTermPrefix === 'ending') {
1662 $to['d'] = $now['mday'];
1663 $to['M'] = $now['mon'];
1664 $to['Y'] = $now['year'];
1666 $to['i'] = $to['s'] = 59;
1667 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1668 $from = self
::intervalAdd('second', 1, $from);
1674 $weekFirst = Civi
::settings()->get('weekBegins');
1675 $thisDay = $now['wday'];
1676 if ($weekFirst > $thisDay) {
1677 $diffDay = $thisDay - $weekFirst +
7;
1680 $diffDay = $thisDay - $weekFirst;
1682 switch ($relativeTerm) {
1684 $from['d'] = $now['mday'];
1685 $from['M'] = $now['mon'];
1686 $from['Y'] = $now['year'];
1687 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1688 $to = self
::intervalAdd('day', 6, $from);
1692 $from['d'] = $now['mday'];
1693 $from['M'] = $now['mon'];
1694 $from['Y'] = $now['year'];
1695 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1696 $to = self
::intervalAdd('day', 6, $from);
1699 case 'previous_before':
1700 $from['d'] = $now['mday'];
1701 $from['M'] = $now['mon'];
1702 $from['Y'] = $now['year'];
1703 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1704 $to = self
::intervalAdd('day', 6, $from);
1708 $from['d'] = $now['mday'];
1709 $from['M'] = $now['mon'];
1710 $from['Y'] = $now['year'];
1711 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1712 $to = self
::intervalAdd('day', 13, $from);
1716 $to['d'] = $now['mday'];
1717 $to['M'] = $now['mon'];
1718 $to['Y'] = $now['year'];
1719 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1724 $from['d'] = $now['mday'];
1725 $from['M'] = $now['mon'];
1726 $from['Y'] = $now['year'];
1727 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1731 case 'greater_previous':
1732 $from['d'] = $now['mday'];
1733 $from['M'] = $now['mon'];
1734 $from['Y'] = $now['year'];
1735 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1740 $to['d'] = $now['mday'];
1741 $to['M'] = $now['mon'];
1742 $to['Y'] = $now['year'];
1744 $to['i'] = $to['s'] = 59;
1745 $from = self
::intervalAdd('day', -7, $to);
1746 $from = self
::intervalAdd('second', 1, $from);
1750 $from['d'] = $now['mday'];
1751 $from['M'] = $now['mon'];
1752 $from['Y'] = $now['year'];
1753 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1754 $to['d'] = $now['mday'];
1755 $to['M'] = $now['mon'];
1756 $to['Y'] = $now['year'];
1758 $to['i'] = $to['s'] = 59;
1762 $to['d'] = $now['mday'];
1763 $to['M'] = $now['mon'];
1764 $to['Y'] = $now['year'];
1766 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1771 $from['d'] = $now['mday'];
1772 $from['M'] = $now['mon'];
1773 $from['Y'] = $now['year'];
1774 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1775 $to = self
::intervalAdd('day', 6, $from);
1779 $from['d'] = $now['mday'];
1780 $from['M'] = $now['mon'];
1781 $from['Y'] = $now['year'];
1783 $from['i'] = $to['s'] = 00;
1784 $to = self
::intervalAdd('day', 7, $from);
1785 $to = self
::intervalAdd('second', -1, $to);
1789 if ($relativeTermPrefix === 'ending') {
1790 $to['d'] = $now['mday'];
1791 $to['M'] = $now['mon'];
1792 $to['Y'] = $now['year'];
1794 $to['i'] = $to['s'] = 59;
1795 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1796 $from = self
::intervalAdd('second', 1, $from);
1802 switch ($relativeTerm) {
1804 $from['d'] = $to['d'] = $now['mday'];
1805 $from['M'] = $to['M'] = $now['mon'];
1806 $from['Y'] = $to['Y'] = $now['year'];
1810 $from['d'] = $now['mday'];
1811 $from['M'] = $now['mon'];
1812 $from['Y'] = $now['year'];
1813 $from = self
::intervalAdd('day', -1, $from);
1814 $to['d'] = $from['d'];
1815 $to['M'] = $from['M'];
1816 $to['Y'] = $from['Y'];
1819 case 'previous_before':
1820 $from['d'] = $now['mday'];
1821 $from['M'] = $now['mon'];
1822 $from['Y'] = $now['year'];
1823 $from = self
::intervalAdd('day', -2, $from);
1824 $to['d'] = $from['d'];
1825 $to['M'] = $from['M'];
1826 $to['Y'] = $from['Y'];
1830 $from['d'] = $to['d'] = $now['mday'];
1831 $from['M'] = $to['M'] = $now['mon'];
1832 $from['Y'] = $to['Y'] = $now['year'];
1833 $from = self
::intervalAdd('day', -2, $from);
1834 $to = self
::intervalAdd('day', -1, $to);
1838 $to['d'] = $now['mday'];
1839 $to['M'] = $now['mon'];
1840 $to['Y'] = $now['year'];
1841 $to = self
::intervalAdd('day', -1, $to);
1846 $from['d'] = $now['mday'];
1847 $from['M'] = $now['mon'];
1848 $from['Y'] = $now['year'];
1853 $to['d'] = $now['mday'];
1854 $to['M'] = $now['mon'];
1855 $to['Y'] = $now['year'];
1856 $to = self
::intervalAdd('day', 1, $to);
1857 $from['d'] = $to['d'];
1858 $from['M'] = $to['M'];
1859 $from['Y'] = $to['Y'];
1863 if ($relativeTermPrefix === 'ending') {
1864 $to['d'] = $now['mday'];
1865 $to['M'] = $now['mon'];
1866 $to['Y'] = $now['year'];
1868 $to['i'] = $to['s'] = 59;
1869 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1870 $from = self
::intervalAdd('second', 1, $from);
1876 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1877 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1882 * Calculate current fiscal year based on the fiscal month and day.
1884 * @param int $fyDate
1885 * Fiscal start date.
1887 * @param int $fyMonth
1888 * Fiscal Start Month.
1891 * $fy Current Fiscal Year
1893 public static function calculateFiscalYear($fyDate, $fyMonth) {
1894 $date = date("Y-m-d");
1895 $currentYear = date("Y");
1897 // recalculate the date because month 4::04 make the difference
1898 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1899 $fyDate = $fiscalYear[2];
1900 $fyMonth = $fiscalYear[1];
1901 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1903 if ($fyStartDate > $date) {
1904 $fy = intval(intval($currentYear) - 1);
1907 $fy = intval($currentYear);
1913 * Function to process date, convert to mysql format
1915 * @param string $date
1917 * @param string $time
1919 * @param bool|string $returnNullString 'null' needs to be returned
1920 * so that db oject will set null in db
1921 * @param string $format
1922 * Expected return date format.( default is mysql ).
1925 * date format that is excepted by mysql
1927 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1930 if ($returnNullString) {
1931 $mysqlDate = 'null';
1935 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1942 * Add the metadata about a date field to the field.
1944 * This metadata will work with the call $form->add('datepicker', ...
1946 * @param array $fieldMetaData
1947 * @param array $field
1951 public static function addDateMetadataToField($fieldMetaData, $field) {
1952 if (isset($fieldMetaData['html'])) {
1953 $field['html_type'] = $fieldMetaData['html']['type'];
1954 if ($field['html_type'] === 'Select Date') {
1955 if (!isset($field['date_format'])) {
1956 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1957 $field['start_date_years'] = $dateAttributes['minYear'];
1958 $field['end_date_years'] = $dateAttributes['maxYear'];
1959 $field['date_format'] = $dateAttributes['format'];
1960 $field['is_datetime_field'] = TRUE;
1961 $field['time_format'] = $dateAttributes['time'];
1962 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1964 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1965 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1972 * Get the fields required for the 'extra' parameter when adding a datepicker.
1974 * @param array $field
1978 public static function getDatePickerExtra($field) {
1980 if (isset($field['date_format'])) {
1981 $extra['date'] = $field['date_format'];
1982 $extra['time'] = $field['time_format'];
1984 $thisYear = date('Y');
1985 if (isset($field['start_date_years'])) {
1986 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1988 if (isset($field['end_date_years'])) {
1989 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1995 * Get the attributes parameters required for datepicker.
1997 * @param array $field
2001 * Array ready to pass to $this->addForm('datepicker' as attributes.
2003 public static function getDatePickerAttributes(&$field) {
2006 'start_date_years' => 'minYear',
2007 'end_date_years' => 'maxYear',
2008 'date_format' => 'format',
2010 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2011 if (isset($field[$dateAttribute])) {
2012 $attributes[$mapTo] = $field[$dateAttribute];
2019 * Function to convert mysql to date plugin format.
2021 * @param string $mysqlDate
2024 * @param null $formatType
2025 * @param null $format
2026 * @param null $timeFormat
2031 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2032 // if date is not passed assume it as today
2034 $mysqlDate = date('Y-m-d G:i:s');
2037 $config = CRM_Core_Config
::singleton();
2039 // get actual format
2040 $params = ['name' => $formatType];
2042 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2044 if ($values['date_format']) {
2045 $format = $values['date_format'];
2048 if (isset($values['time_format'])) {
2049 $timeFormat = $values['time_format'];
2053 $dateFormat = 'm/d/Y';
2054 $date = date($dateFormat, strtotime($mysqlDate));
2057 $timeFormat = $config->timeInputFormat
;
2060 $actualTimeFormat = "g:iA";
2061 $appendZeroLength = 7;
2062 if ($timeFormat > 1) {
2063 $actualTimeFormat = "G:i";
2064 $appendZeroLength = 5;
2067 $time = date($actualTimeFormat, strtotime($mysqlDate));
2069 // need to append zero for hours < 10
2070 if (strlen($time) < $appendZeroLength) {
2071 $time = '0' . $time;
2074 return [$date, $time];
2078 * Function get date format.
2080 * @param string $formatType
2081 * Date name e.g. birth.
2085 public static function getDateFormat($formatType = NULL) {
2088 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2089 $formatType, 'date_format', 'name'
2094 $config = CRM_Core_Config
::singleton();
2095 $format = $config->dateInputFormat
;
2104 * @return null|string
2106 public static function formatDate($date, $dateType) {
2107 $formattedDate = NULL;
2109 return $formattedDate;
2112 // 1. first convert date to default format.
2113 // 2. append time to default formatted date (might be removed during format)
2114 // 3. validate date / date time.
2115 // 4. If date and time then convert to default date time format.
2118 $dateParams = [$dateKey => $date];
2120 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2121 $dateVal = $dateParams[$dateKey];
2123 if ($dateType == 1) {
2125 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2126 $ruleName = 'dateTime';
2127 if (strpos($date, '-') !== FALSE) {
2128 $dateVal .= array_shift($matches);
2134 $valid = CRM_Utils_Rule
::$ruleName($dateVal);
2137 // format date and time to default.
2138 if ($ruleName == 'dateTime') {
2139 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2140 // hack to add seconds
2143 $formattedDate = $dateVal;
2147 return $formattedDate;
2151 * Function to return days of the month.
2155 public static function getCalendarDayOfMonth() {
2157 for ($i = 1; $i <= 31; $i++
) {
2160 $month[$i] = $i . ' / Last day of month';
2167 * Convert a relative date format to an api field.
2169 * @param array $params
2170 * @param string $dateField
2171 * @param bool $isDatePicker
2172 * Non datepicker fields are deprecated. Exterminate Exterminate.
2173 * (but for now handle them).
2175 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2176 if (!empty($params[$dateField . '_relative'])) {
2177 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2178 unset($params[$dateField . '_relative']);
2180 if (!empty($params[$dateField . '_low'])) {
2181 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2182 unset($params[$dateField . '_low']);
2184 if (!empty($params[$dateField . '_high'])) {
2185 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2186 unset($params[$dateField . '_high']);
2188 if (empty($dates)) {
2191 if (empty($dates[0])) {
2192 $params[$dateField] = ['<=' => $dates[1]];
2194 elseif (empty($dates[1])) {
2195 $params[$dateField] = ['>=' => $dates[0]];
2198 $params[$dateField] = ['BETWEEN' => $dates];
2203 * Print out a date object in specified format in local timezone
2205 * @param DateTimeObject $dateObject
2206 * @param string $format
2209 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2210 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2211 $dateObject->setTimezone($systemTimeZone);
2212 return $dateObject->format($format);