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, $to, $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
898 * array $results contains years or months
900 public static function calculateAge($birthDate) {
902 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
904 $bDate = explode('-', $formatedBirthDate);
905 $birthYear = $bDate[0];
906 $birthMonth = $bDate[1];
907 $birthDay = $bDate[2];
908 $year_diff = date("Y") - $birthYear;
910 // don't calculate age CRM-3143
911 if ($birthYear == '1902') {
915 switch ($year_diff) {
917 $month = (12 - $birthMonth) +
date("m");
919 if (date("d") < $birthDay) {
922 $results['months'] = $month;
924 elseif ($month == 12 && (date("d") < $birthDay)) {
925 $results['months'] = $month - 1;
928 $results['years'] = $year_diff;
933 $month = date("m") - $birthMonth;
934 $results['months'] = $month;
938 $results['years'] = $year_diff;
939 if ((date("m") < $birthMonth) ||
(date("m") == $birthMonth) && (date("d") < $birthDay)) {
948 * Calculate next payment date according to provided unit & interval
950 * @param string $unit
951 * Frequency unit like year,month, week etc.
953 * @param int $interval
954 * Frequency interval.
957 * Start date of pledge.
959 * @param bool $dontCareTime
962 * contains new date with added interval
964 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
965 if (is_array($date)) {
966 $hour = $date['H'] ??
NULL;
967 $minute = $date['i'] ??
NULL;
968 $second = $date['s'] ??
NULL;
969 $month = $date['M'] ??
NULL;
970 $day = $date['d'] ??
NULL;
971 $year = $date['Y'] ??
NULL;
974 extract(date_parse($date));
976 $date = mktime($hour, $minute, $second, $month, $day, $year);
979 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
983 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
987 $interval = $interval * 7;
988 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
992 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
996 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1000 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1003 $date['M'] = $scheduleDate[0];
1004 $date['d'] = $scheduleDate[1];
1005 $date['Y'] = $scheduleDate[2];
1006 if ($dontCareTime == FALSE) {
1007 $date['H'] = $scheduleDate[3];
1008 $date['i'] = $scheduleDate[4];
1009 $date['s'] = $scheduleDate[5];
1015 * Get the smarty view presentation mapping for the given format.
1017 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1018 * they should be rendered using a longer date format. This is likely as much to
1019 * do with the earlier date widget being unable to handle some formats as usablity.
1020 * However, we continue to respect this.
1023 * Given format ( eg 'M Y', 'Y M' ).
1025 * @return string|null
1026 * Smarty translation of the date format. Null is also valid and is translated
1027 * according to the available parts at the smarty layer.
1029 public static function getDateFieldViewFormat($format) {
1030 $supportableFormats = [
1031 'mm/dd' => '%B %E%f',
1032 'dd-mm' => '%E%f %B',
1036 'dd/mm/yy' => '%E%f %B %Y',
1039 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1043 * Pick the smarty format from settings that best matches the time string we have.
1045 * For view purposes we historically use the setting that most closely matches the data
1046 * in the format from our settings, as opposed to the setting configured for the field.
1051 public static function pickBestSmartyFormat($format) {
1052 if (stristr($format, 'h')) {
1053 return Civi
::settings()->get('dateformatDatetime');
1055 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1056 return Civi
::settings()->get('dateformatFull');
1058 if (stristr($format, 'm')) {
1059 return Civi
::settings()->get('dateformatPartial');
1061 return Civi
::settings()->get('dateformatYear');
1065 * Map date plugin and actual format that is used by PHP.
1069 public static function datePluginToPHPFormats() {
1070 $dateInputFormats = [
1071 "mm/dd/yy" => 'm/d/Y',
1072 "dd/mm/yy" => 'd/m/Y',
1073 "yy-mm-dd" => 'Y-m-d',
1074 "dd-mm-yy" => 'd-m-Y',
1075 "dd.mm.yy" => 'd.m.Y',
1077 "M d, yy" => 'M j, Y',
1078 "d M yy" => 'j M Y',
1079 "MM d, yy" => 'F j, Y',
1080 "d MM yy" => 'j F Y',
1081 "DD, d MM yy" => 'l, j F Y',
1089 return $dateInputFormats;
1093 * Resolves the given relative time interval into finite time limits.
1095 * @param string $relativeTerm
1096 * Relative time frame: this, previous, previous_1.
1098 * Frequency unit like year, month, week etc.
1101 * start date and end date for the relative time frame
1103 public static function relativeToAbsolute($relativeTerm, $unit) {
1105 $from = $to = $dateRange = [];
1106 $from['H'] = $from['i'] = $from['s'] = 0;
1107 $relativeTermParts = explode('_', $relativeTerm);
1108 $relativeTermPrefix = $relativeTermParts[0];
1109 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1113 switch ($relativeTerm) {
1115 $from['M'] = $from['d'] = 1;
1118 $to['Y'] = $from['Y'] = $now['year'] - 1;
1121 case 'previous_before':
1122 $from['M'] = $from['d'] = 1;
1125 $to['Y'] = $from['Y'] = $now['year'] - 2;
1129 $from['M'] = $from['d'] = 1;
1132 $from['Y'] = $now['year'] - 2;
1133 $to['Y'] = $now['year'] - 1;
1139 $to['Y'] = $now['year'] - 1;
1144 $from['M'] = $from['d'] = 1;
1145 $from['Y'] = $now['year'];
1149 case 'greater_previous':
1152 $from['Y'] = $now['year'] - 1;
1157 $to['d'] = $now['mday'];
1158 $to['M'] = $now['mon'];
1159 $to['Y'] = $now['year'];
1161 $to['i'] = $to['s'] = 59;
1162 $from = self
::intervalAdd('year', -1, $to);
1163 $from = self
::intervalAdd('second', 1, $from);
1167 $from['M'] = $from['d'] = 1;
1168 $from['Y'] = $now['year'];
1170 $to['i'] = $to['s'] = 59;
1171 $to['d'] = $now['mday'];
1172 $to['M'] = $now['mon'];
1173 $to['Y'] = $now['year'];
1177 $to['d'] = $now['mday'];
1178 $to['M'] = $now['mon'];
1179 $to['Y'] = $now['year'];
1181 $to['i'] = $to['s'] = 59;
1182 $from = self
::intervalAdd('year', -2, $to);
1183 $from = self
::intervalAdd('second', 1, $from);
1187 $to['d'] = $now['mday'];
1188 $to['M'] = $now['mon'];
1189 $to['Y'] = $now['year'];
1191 $to['i'] = $to['s'] = 59;
1192 $from = self
::intervalAdd('year', -3, $to);
1193 $from = self
::intervalAdd('second', 1, $from);
1199 $to['Y'] = $now['year'];
1204 $from['M'] = $from['d'] = 1;
1207 $to['Y'] = $from['Y'] = $now['year'] +
1;
1211 $from['d'] = $now['mday'];
1212 $from['M'] = $now['mon'];
1213 $from['Y'] = $now['year'];
1214 $to['d'] = $now['mday'] - 1;
1215 $to['M'] = $now['mon'];
1216 $to['Y'] = $now['year'] +
1;
1220 switch ($relativeTermPrefix) {
1223 $to['d'] = $now['mday'];
1224 $to['M'] = $now['mon'];
1225 $to['Y'] = $now['year'];
1227 $to['i'] = $to['s'] = 59;
1228 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1229 $from = self
::intervalAdd('second', 1, $from);
1233 $from['d'] = $from['M'] = 1;
1236 $to['Y'] = $from['Y'] = $now['year'];
1237 if (is_numeric($relativeTermSuffix)) {
1238 $from['Y'] -= ($relativeTermSuffix - 1);
1247 $config = CRM_Core_Config
::singleton();
1248 $from['d'] = $config->fiscalYearStart
['d'];
1249 $from['M'] = $config->fiscalYearStart
['M'];
1250 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1251 switch ($relativeTermPrefix) {
1253 $from['Y'] = $fYear;
1254 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1255 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1256 $to['d'] = $fiscalEnd['2'];
1257 $to['M'] = $fiscalEnd['1'];
1258 $to['Y'] = $fiscalEnd['0'];
1260 $to['i'] = $to['s'] = 59;
1261 if (is_numeric($relativeTermSuffix)) {
1262 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1263 $from = self
::intervalAdd('second', 1, $from);
1268 if (!is_numeric($relativeTermSuffix)) {
1269 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1270 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1271 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1272 $to['d'] = $fiscalEnd['2'];
1273 $to['M'] = $fiscalEnd['1'];
1274 $to['Y'] = $fiscalEnd['0'];
1276 $to['i'] = $to['s'] = 59;
1279 $from['Y'] = $fYear - $relativeTermSuffix;
1280 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1281 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1282 $to['d'] = $fiscalEnd['2'];
1283 $to['M'] = $fiscalEnd['1'];
1286 $to['i'] = $to['s'] = 59;
1291 $from['Y'] = $fYear +
1;
1292 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1293 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1294 $to['d'] = $fiscalEnd['2'];
1295 $to['M'] = $fiscalEnd['1'];
1296 $to['Y'] = $fiscalEnd['0'];
1302 switch ($relativeTerm) {
1305 $quarter = ceil($now['mon'] / 3);
1307 $from['M'] = (3 * $quarter) - 2;
1308 $to['M'] = 3 * $quarter;
1309 $to['Y'] = $from['Y'] = $now['year'];
1310 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1315 $quarter = ceil($now['mon'] / 3);
1316 $quarter = $quarter - $difference;
1318 if ($quarter <= 0) {
1323 $from['M'] = (3 * $quarter) - 2;
1324 $to['M'] = 3 * $quarter;
1325 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1326 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1329 case 'previous_before':
1331 $quarter = ceil($now['mon'] / 3);
1332 $quarter = $quarter - $difference;
1334 if ($quarter <= 0) {
1339 $from['M'] = (3 * $quarter) - 2;
1340 $to['M'] = 3 * $quarter;
1341 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1342 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1347 $quarter = ceil($now['mon'] / 3);
1348 $current_quarter = $quarter;
1349 $quarter = $quarter - $difference;
1351 if ($quarter <= 0) {
1356 $from['M'] = (3 * $quarter) - 2;
1357 switch ($current_quarter) {
1359 $to['M'] = (4 * $quarter);
1363 $to['M'] = (4 * $quarter) +
3;
1367 $to['M'] = (4 * $quarter) +
2;
1371 $to['M'] = (4 * $quarter) +
1;
1374 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1375 if ($to['M'] > 12) {
1376 $to['M'] = 3 * ($quarter - 3);
1377 $to['Y'] = $now['year'];
1379 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1383 $quarter = ceil($now['mon'] / 3) - 1;
1385 if ($quarter <= 0) {
1389 $to['M'] = 3 * $quarter;
1390 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1391 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1396 $quarter = ceil($now['mon'] / 3);
1398 $from['M'] = (3 * $quarter) - 2;
1399 $from['Y'] = $now['year'];
1403 case 'greater_previous':
1404 $quarter = ceil($now['mon'] / 3) - 1;
1406 if ($quarter <= 0) {
1410 $from['M'] = 3 * $quarter;
1411 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1412 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1417 $to['d'] = $now['mday'];
1418 $to['M'] = $now['mon'];
1419 $to['Y'] = $now['year'];
1421 $to['i'] = $to['s'] = 59;
1422 $from = self
::intervalAdd('day', -90, $to);
1423 $from = self
::intervalAdd('second', 1, $from);
1427 $quarter = ceil($now['mon'] / 3);
1429 $from['M'] = (3 * $quarter) - 2;
1430 $from['Y'] = $now['year'];
1431 $to['d'] = $now['mday'];
1432 $to['M'] = $now['mon'];
1433 $to['Y'] = $now['year'];
1435 $to['i'] = $to['s'] = 59;
1439 $quarter = ceil($now['mon'] / 3);
1440 $to['M'] = 3 * $quarter;
1441 $to['Y'] = $now['year'];
1442 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1449 $quarter = ceil($now['mon'] / 3);
1450 $quarter = $quarter - $difference;
1453 $now['year'] = $now['year'] +
1;
1456 if ($quarter <= 0) {
1461 $from['M'] = (3 * $quarter) - 2;
1462 $to['M'] = 3 * $quarter;
1463 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1464 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1468 $from['d'] = $now['mday'];
1469 $from['M'] = $now['mon'];
1470 $from['Y'] = $now['year'];
1472 $from['i'] = $to['s'] = 00;
1473 $to = self
::intervalAdd('day', 90, $from);
1474 $to = self
::intervalAdd('second', -1, $to);
1478 if ($relativeTermPrefix === 'ending') {
1479 $to['d'] = $now['mday'];
1480 $to['M'] = $now['mon'];
1481 $to['Y'] = $now['year'];
1483 $to['i'] = $to['s'] = 59;
1484 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1485 $from = self
::intervalAdd('second', 1, $from);
1491 switch ($relativeTerm) {
1494 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1495 $from['M'] = $to['M'] = $now['mon'];
1496 $from['Y'] = $to['Y'] = $now['year'];
1501 if ($now['mon'] == 1) {
1502 $from['M'] = $to['M'] = 12;
1503 $from['Y'] = $to['Y'] = $now['year'] - 1;
1506 $from['M'] = $to['M'] = $now['mon'] - 1;
1507 $from['Y'] = $to['Y'] = $now['year'];
1509 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1512 case 'previous_before':
1514 if ($now['mon'] < 3) {
1515 $from['M'] = $to['M'] = 10 +
$now['mon'];
1516 $from['Y'] = $to['Y'] = $now['year'] - 1;
1519 $from['M'] = $to['M'] = $now['mon'] - 2;
1520 $from['Y'] = $to['Y'] = $now['year'];
1522 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1527 if ($now['mon'] < 3) {
1528 $from['M'] = 10 +
$now['mon'];
1529 $from['Y'] = $now['year'] - 1;
1532 $from['M'] = $now['mon'] - 2;
1533 $from['Y'] = $now['year'];
1536 if ($now['mon'] == 1) {
1538 $to['Y'] = $now['year'] - 1;
1541 $to['M'] = $now['mon'] - 1;
1542 $to['Y'] = $now['year'];
1545 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1549 // before end of past month
1550 if ($now['mon'] == 1) {
1552 $to['Y'] = $now['year'] - 1;
1555 $to['M'] = $now['mon'] - 1;
1556 $to['Y'] = $now['year'];
1559 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1565 $from['M'] = $now['mon'];
1566 $from['Y'] = $now['year'];
1570 case 'greater_previous':
1571 // from end of past month
1572 if ($now['mon'] == 1) {
1574 $from['Y'] = $now['year'] - 1;
1577 $from['M'] = $now['mon'] - 1;
1578 $from['Y'] = $now['year'];
1581 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1586 $to['d'] = $now['mday'];
1587 $to['M'] = $now['mon'];
1588 $to['Y'] = $now['year'];
1590 $to['i'] = $to['s'] = 59;
1591 $from = self
::intervalAdd('day', -60, $to);
1592 $from = self
::intervalAdd('second', 1, $from);
1596 $to['d'] = $now['mday'];
1597 $to['M'] = $now['mon'];
1598 $to['Y'] = $now['year'];
1600 $to['i'] = $to['s'] = 59;
1601 $from = self
::intervalAdd('day', -30, $to);
1602 $from = self
::intervalAdd('second', 1, $from);
1607 $from['M'] = $now['mon'];
1608 $from['Y'] = $now['year'];
1609 $to['d'] = $now['mday'];
1610 $to['M'] = $now['mon'];
1611 $to['Y'] = $now['year'];
1613 $to['i'] = $to['s'] = 59;
1618 $to['Y'] = $now['year'];
1619 $to['M'] = $now['mon'];
1620 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1626 if ($now['mon'] == 12) {
1627 $from['M'] = $to['M'] = 1;
1628 $from['Y'] = $to['Y'] = $now['year'] +
1;
1631 $from['M'] = $to['M'] = $now['mon'] +
1;
1632 $from['Y'] = $to['Y'] = $now['year'];
1634 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1638 $from['d'] = $now['mday'];
1639 $from['M'] = $now['mon'];
1640 $from['Y'] = $now['year'];
1642 $from['i'] = $to['s'] = 00;
1643 $to = self
::intervalAdd('day', 30, $from);
1644 $to = self
::intervalAdd('second', -1, $to);
1648 $from['d'] = $now['mday'];
1649 $from['M'] = $now['mon'];
1650 $from['Y'] = $now['year'];
1652 $from['i'] = $to['s'] = 00;
1653 $to = self
::intervalAdd('day', 60, $from);
1654 $to = self
::intervalAdd('second', -1, $to);
1658 if ($relativeTermPrefix === 'ending') {
1659 $to['d'] = $now['mday'];
1660 $to['M'] = $now['mon'];
1661 $to['Y'] = $now['year'];
1663 $to['i'] = $to['s'] = 59;
1664 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1665 $from = self
::intervalAdd('second', 1, $from);
1671 $weekFirst = Civi
::settings()->get('weekBegins');
1672 $thisDay = $now['wday'];
1673 if ($weekFirst > $thisDay) {
1674 $diffDay = $thisDay - $weekFirst +
7;
1677 $diffDay = $thisDay - $weekFirst;
1679 switch ($relativeTerm) {
1681 $from['d'] = $now['mday'];
1682 $from['M'] = $now['mon'];
1683 $from['Y'] = $now['year'];
1684 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1685 $to = self
::intervalAdd('day', 6, $from);
1689 $from['d'] = $now['mday'];
1690 $from['M'] = $now['mon'];
1691 $from['Y'] = $now['year'];
1692 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1693 $to = self
::intervalAdd('day', 6, $from);
1696 case 'previous_before':
1697 $from['d'] = $now['mday'];
1698 $from['M'] = $now['mon'];
1699 $from['Y'] = $now['year'];
1700 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1701 $to = self
::intervalAdd('day', 6, $from);
1705 $from['d'] = $now['mday'];
1706 $from['M'] = $now['mon'];
1707 $from['Y'] = $now['year'];
1708 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1709 $to = self
::intervalAdd('day', 13, $from);
1713 $to['d'] = $now['mday'];
1714 $to['M'] = $now['mon'];
1715 $to['Y'] = $now['year'];
1716 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1721 $from['d'] = $now['mday'];
1722 $from['M'] = $now['mon'];
1723 $from['Y'] = $now['year'];
1724 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1728 case 'greater_previous':
1729 $from['d'] = $now['mday'];
1730 $from['M'] = $now['mon'];
1731 $from['Y'] = $now['year'];
1732 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1737 $to['d'] = $now['mday'];
1738 $to['M'] = $now['mon'];
1739 $to['Y'] = $now['year'];
1741 $to['i'] = $to['s'] = 59;
1742 $from = self
::intervalAdd('day', -7, $to);
1743 $from = self
::intervalAdd('second', 1, $from);
1747 $from['d'] = $now['mday'];
1748 $from['M'] = $now['mon'];
1749 $from['Y'] = $now['year'];
1750 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1751 $to['d'] = $now['mday'];
1752 $to['M'] = $now['mon'];
1753 $to['Y'] = $now['year'];
1755 $to['i'] = $to['s'] = 59;
1759 $to['d'] = $now['mday'];
1760 $to['M'] = $now['mon'];
1761 $to['Y'] = $now['year'];
1763 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1768 $from['d'] = $now['mday'];
1769 $from['M'] = $now['mon'];
1770 $from['Y'] = $now['year'];
1771 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1772 $to = self
::intervalAdd('day', 6, $from);
1776 $from['d'] = $now['mday'];
1777 $from['M'] = $now['mon'];
1778 $from['Y'] = $now['year'];
1780 $from['i'] = $to['s'] = 00;
1781 $to = self
::intervalAdd('day', 7, $from);
1782 $to = self
::intervalAdd('second', -1, $to);
1786 if ($relativeTermPrefix === 'ending') {
1787 $to['d'] = $now['mday'];
1788 $to['M'] = $now['mon'];
1789 $to['Y'] = $now['year'];
1791 $to['i'] = $to['s'] = 59;
1792 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1793 $from = self
::intervalAdd('second', 1, $from);
1799 switch ($relativeTerm) {
1801 $from['d'] = $to['d'] = $now['mday'];
1802 $from['M'] = $to['M'] = $now['mon'];
1803 $from['Y'] = $to['Y'] = $now['year'];
1807 $from['d'] = $now['mday'];
1808 $from['M'] = $now['mon'];
1809 $from['Y'] = $now['year'];
1810 $from = self
::intervalAdd('day', -1, $from);
1811 $to['d'] = $from['d'];
1812 $to['M'] = $from['M'];
1813 $to['Y'] = $from['Y'];
1816 case 'previous_before':
1817 $from['d'] = $now['mday'];
1818 $from['M'] = $now['mon'];
1819 $from['Y'] = $now['year'];
1820 $from = self
::intervalAdd('day', -2, $from);
1821 $to['d'] = $from['d'];
1822 $to['M'] = $from['M'];
1823 $to['Y'] = $from['Y'];
1827 $from['d'] = $to['d'] = $now['mday'];
1828 $from['M'] = $to['M'] = $now['mon'];
1829 $from['Y'] = $to['Y'] = $now['year'];
1830 $from = self
::intervalAdd('day', -2, $from);
1831 $to = self
::intervalAdd('day', -1, $to);
1835 $to['d'] = $now['mday'];
1836 $to['M'] = $now['mon'];
1837 $to['Y'] = $now['year'];
1838 $to = self
::intervalAdd('day', -1, $to);
1843 $from['d'] = $now['mday'];
1844 $from['M'] = $now['mon'];
1845 $from['Y'] = $now['year'];
1850 $to['d'] = $now['mday'];
1851 $to['M'] = $now['mon'];
1852 $to['Y'] = $now['year'];
1853 $to = self
::intervalAdd('day', 1, $to);
1854 $from['d'] = $to['d'];
1855 $from['M'] = $to['M'];
1856 $from['Y'] = $to['Y'];
1860 if ($relativeTermPrefix === 'ending') {
1861 $to['d'] = $now['mday'];
1862 $to['M'] = $now['mon'];
1863 $to['Y'] = $now['year'];
1865 $to['i'] = $to['s'] = 59;
1866 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1867 $from = self
::intervalAdd('second', 1, $from);
1873 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1874 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1879 * Calculate current fiscal year based on the fiscal month and day.
1881 * @param int $fyDate
1882 * Fiscal start date.
1884 * @param int $fyMonth
1885 * Fiscal Start Month.
1888 * $fy Current Fiscal Year
1890 public static function calculateFiscalYear($fyDate, $fyMonth) {
1891 $date = date("Y-m-d");
1892 $currentYear = date("Y");
1894 // recalculate the date because month 4::04 make the difference
1895 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1896 $fyDate = $fiscalYear[2];
1897 $fyMonth = $fiscalYear[1];
1898 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1900 if ($fyStartDate > $date) {
1901 $fy = intval(intval($currentYear) - 1);
1904 $fy = intval($currentYear);
1910 * Function to process date, convert to mysql format
1912 * @param string $date
1914 * @param string $time
1916 * @param bool|string $returnNullString 'null' needs to be returned
1917 * so that db oject will set null in db
1918 * @param string $format
1919 * Expected return date format.( default is mysql ).
1922 * date format that is excepted by mysql
1924 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1927 if ($returnNullString) {
1928 $mysqlDate = 'null';
1932 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1939 * Add the metadata about a date field to the field.
1941 * This metadata will work with the call $form->add('datepicker', ...
1943 * @param array $fieldMetaData
1944 * @param array $field
1948 public static function addDateMetadataToField($fieldMetaData, $field) {
1949 if (isset($fieldMetaData['html'])) {
1950 $field['html_type'] = $fieldMetaData['html']['type'];
1951 if ($field['html_type'] === 'Select Date') {
1952 if (!isset($field['date_format'])) {
1953 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1954 $field['start_date_years'] = $dateAttributes['minYear'];
1955 $field['end_date_years'] = $dateAttributes['maxYear'];
1956 $field['date_format'] = $dateAttributes['format'];
1957 $field['is_datetime_field'] = TRUE;
1958 $field['time_format'] = $dateAttributes['time'];
1959 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1961 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1962 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1969 * Get the fields required for the 'extra' parameter when adding a datepicker.
1971 * @param array $field
1975 public static function getDatePickerExtra($field) {
1977 if (isset($field['date_format'])) {
1978 $extra['date'] = $field['date_format'];
1979 $extra['time'] = $field['time_format'];
1981 $thisYear = date('Y');
1982 if (isset($field['start_date_years'])) {
1983 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1985 if (isset($field['end_date_years'])) {
1986 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1992 * Get the attributes parameters required for datepicker.
1994 * @param array $field
1998 * Array ready to pass to $this->addForm('datepicker' as attributes.
2000 public static function getDatePickerAttributes(&$field) {
2003 'start_date_years' => 'minYear',
2004 'end_date_years' => 'maxYear',
2005 'date_format' => 'format',
2007 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2008 if (isset($field[$dateAttribute])) {
2009 $attributes[$mapTo] = $field[$dateAttribute];
2016 * Function to convert mysql to date plugin format.
2018 * @param string $mysqlDate
2021 * @param null $formatType
2022 * @param null $format
2023 * @param null $timeFormat
2028 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2029 // if date is not passed assume it as today
2031 $mysqlDate = date('Y-m-d G:i:s');
2034 $config = CRM_Core_Config
::singleton();
2036 // get actual format
2037 $params = ['name' => $formatType];
2039 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2041 if ($values['date_format']) {
2042 $format = $values['date_format'];
2045 if (isset($values['time_format'])) {
2046 $timeFormat = $values['time_format'];
2050 $dateFormat = 'm/d/Y';
2051 $date = date($dateFormat, strtotime($mysqlDate));
2054 $timeFormat = $config->timeInputFormat
;
2057 $actualTimeFormat = "g:iA";
2058 $appendZeroLength = 7;
2059 if ($timeFormat > 1) {
2060 $actualTimeFormat = "G:i";
2061 $appendZeroLength = 5;
2064 $time = date($actualTimeFormat, strtotime($mysqlDate));
2066 // need to append zero for hours < 10
2067 if (strlen($time) < $appendZeroLength) {
2068 $time = '0' . $time;
2071 return [$date, $time];
2075 * Function get date format.
2077 * @param string $formatType
2078 * Date name e.g. birth.
2082 public static function getDateFormat($formatType = NULL) {
2085 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2086 $formatType, 'date_format', 'name'
2091 $config = CRM_Core_Config
::singleton();
2092 $format = $config->dateInputFormat
;
2101 * @return null|string
2103 public static function formatDate($date, $dateType) {
2104 $formattedDate = NULL;
2106 return $formattedDate;
2109 // 1. first convert date to default format.
2110 // 2. append time to default formatted date (might be removed during format)
2111 // 3. validate date / date time.
2112 // 4. If date and time then convert to default date time format.
2115 $dateParams = [$dateKey => $date];
2117 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2118 $dateVal = $dateParams[$dateKey];
2120 if ($dateType == 1) {
2122 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2123 $ruleName = 'dateTime';
2124 if (strpos($date, '-') !== FALSE) {
2125 $dateVal .= array_shift($matches);
2131 $valid = CRM_Utils_Rule
::$ruleName($dateVal);
2134 // format date and time to default.
2135 if ($ruleName == 'dateTime') {
2136 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2137 // hack to add seconds
2140 $formattedDate = $dateVal;
2144 return $formattedDate;
2148 * Function to return days of the month.
2152 public static function getCalendarDayOfMonth() {
2154 for ($i = 1; $i <= 31; $i++
) {
2157 $month[$i] = $i . ' / Last day of month';
2164 * Convert a relative date format to an api field.
2166 * @param array $params
2167 * @param string $dateField
2168 * @param bool $isDatePicker
2169 * Non datepicker fields are deprecated. Exterminate Exterminate.
2170 * (but for now handle them).
2172 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2173 if (!empty($params[$dateField . '_relative'])) {
2174 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2175 unset($params[$dateField . '_relative']);
2177 if (!empty($params[$dateField . '_low'])) {
2178 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2179 unset($params[$dateField . '_low']);
2181 if (!empty($params[$dateField . '_high'])) {
2182 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2183 unset($params[$dateField . '_high']);
2185 if (empty($dates)) {
2188 if (empty($dates[0])) {
2189 $params[$dateField] = ['<=' => $dates[1]];
2191 elseif (empty($dates[1])) {
2192 $params[$dateField] = ['>=' => $dates[0]];
2195 $params[$dateField] = ['BETWEEN' => $dates];
2200 * Print out a date object in specified format in local timezone
2202 * @param DateTimeObject $dateObject
2203 * @param string $format
2206 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2207 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2208 $dateObject->setTimezone($systemTimeZone);
2209 return $dateObject->format($format);