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 seperator 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' => CRM_Utils_Array
::value($month, $abbrMonths),
399 '%B' => CRM_Utils_Array
::value($month, $fullMonths),
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 * Wrapper for customFormat that takes a timestamp
428 * @param int $timestamp
429 * Date and time in timestamp format.
430 * @param string $format
432 * @param array $dateParts
433 * An array with the desired date parts.
436 * the $format-formatted $date
438 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
439 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
443 * Converts the date/datetime from MySQL format to ISO format
445 * @param string $mysql
446 * Date/datetime in MySQL format.
449 * date/datetime in ISO format
451 public static function mysqlToIso($mysql) {
452 $year = substr($mysql, 0, 4);
453 $month = substr($mysql, 4, 2);
454 $day = substr($mysql, 6, 2);
455 $hour = substr($mysql, 8, 2);
456 $minute = substr($mysql, 10, 2);
457 $second = substr($mysql, 12, 2);
483 * Converts the date/datetime from ISO format to MySQL format
484 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
485 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
486 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
489 * Date/datetime in ISO format.
492 * date/datetime in MySQL format
494 public static function isoToMysql($iso) {
495 $dropArray = ['-' => '', ':' => '', ' ' => ''];
496 return strtr($iso, $dropArray);
500 * Converts the any given date to default date format.
502 * @param array $params
503 * Has given date-format.
504 * @param int $dateType
506 * @param string $dateParam
511 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
513 $cen = substr($now['year'], 0, 2);
517 if (!empty($params[$dateParam])) {
518 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
519 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
524 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
530 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
536 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
542 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
548 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
554 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
560 if ($dateType == 1) {
561 $formattedDate = explode("-", $value);
562 if (count($formattedDate) == 3) {
563 $year = (int) $formattedDate[0];
564 $month = (int) $formattedDate[1];
565 $day = (int) $formattedDate[2];
567 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
575 if ($dateType == 2 ||
$dateType == 4) {
576 $formattedDate = explode("/", $value);
577 if (count($formattedDate) != 3) {
578 $formattedDate = explode("-", $value);
580 if (count($formattedDate) == 3) {
581 $year = (int) $formattedDate[2];
582 $month = (int) $formattedDate[0];
583 $day = (int) $formattedDate[1];
589 if ($dateType == 8) {
590 $dateArray = explode(' ', $value);
592 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
595 $fullMonths = self
::getFullMonthNames();
596 foreach ($fullMonths as $key => $val) {
597 if (strtolower($dateArray[0]) == strtolower($val)) {
603 $abbrMonths = self
::getAbbrMonthNames();
604 foreach ($abbrMonths as $key => $val) {
605 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
611 $year = (int) $dateArray[2];
612 $day = (int) $dateArray[1];
613 $month = (int) $monthInt;
615 if ($dateType == 16) {
616 $dateArray = explode('-', $value);
617 if (count($dateArray) != 3) {
618 $dateArray = explode('/', $value);
621 if (count($dateArray) == 3) {
623 $fullMonths = self
::getFullMonthNames();
624 foreach ($fullMonths as $key => $val) {
625 if (strtolower($dateArray[1]) == strtolower($val)) {
631 $abbrMonths = self
::getAbbrMonthNames();
632 foreach ($abbrMonths as $key => $val) {
633 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
640 $monthInt = $dateArray[1];
643 $year = (int) $dateArray[2];
644 $day = (int) $dateArray[0];
645 $month = (int) $monthInt;
651 if ($dateType == 32) {
652 $formattedDate = explode("/", $value);
653 if (count($formattedDate) == 3) {
654 $year = (int) $formattedDate[2];
655 $month = (int) $formattedDate[1];
656 $day = (int) $formattedDate[0];
663 $month = ($month < 10) ?
"0" . "$month" : $month;
664 $day = ($day < 10) ?
"0" . "$day" : $day;
666 $year = (int ) $year;
667 // simple heuristic to determine what century to use
668 // 00 - 20 is always 2000 - 2020
669 // 21 - 99 is always 1921 - 1999
671 $year = (strlen($year) == 1) ?
$cen . '0' . $year : $cen . $year;
673 elseif ($year < 100) {
674 $year = $prevCen . $year;
677 if ($params[$dateParam]) {
678 $params[$dateParam] = "$year$month$day";
680 // if month is invalid return as error
681 if ($month !== '00' && $month <= 12) {
692 public static function isDate(&$date) {
693 if (CRM_Utils_System
::isNull($date)) {
700 * Translate a TTL to a concrete expiration time.
702 * @param NULL|int|DateInterval $ttl
703 * @param int $default
704 * The value to use if $ttl is not specified (NULL).
706 * Timestamp (seconds since epoch).
707 * @throws \CRM_Utils_Cache_InvalidArgumentException
709 public static function convertCacheTtlToExpires($ttl, $default) {
715 return time() +
$ttl;
717 elseif ($ttl instanceof DateInterval
) {
718 return date_add(new DateTime(), $ttl)->getTimestamp();
721 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
728 * @param NULL|int|DateInterval $ttl
729 * @param int $default
730 * The value to use if $ttl is not specified (NULL).
732 * Seconds until expiration.
733 * @throws \CRM_Utils_Cache_InvalidArgumentException
735 public static function convertCacheTtl($ttl, $default) {
739 elseif (is_int($ttl)) {
742 elseif ($ttl instanceof DateInterval
) {
743 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
746 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
751 * @param null $timeStamp
753 * @return bool|string
755 public static function currentDBDate($timeStamp = NULL) {
756 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
765 public static function overdue($date, $now = NULL) {
766 $mysqlDate = self
::isoToMysql($date);
768 $now = self
::currentDBDate();
771 $now = self
::isoToMysql($now);
774 return (strtotime($mysqlDate) >= strtotime($now)) ?
FALSE : TRUE;
778 * Get customized today.
780 * This function is used for getting customized today. To get
781 * actuall today pass 'dayParams' as null. or else pass the day,
782 * month, year values as array values
783 * Example: $dayParams = array(
784 * 'day' => '25', 'month' => '10',
785 * 'year' => '2007' );
787 * @param array $dayParams of the day, month, year.
788 * Array of the day, month, year.
790 * @param string $format
791 * Expected date format( default.
792 * format is 2007-12-21 )
795 * Return the customized today's date (Y-m-d)
797 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
798 if (is_null($dayParams) ||
empty($dayParams)) {
799 $today = date($format);
802 $today = date($format, mktime(0, 0, 0,
813 * Find whether today's date lies in
816 * @param date $startDate
817 * Start date for the range.
818 * @param date $endDate
819 * End date for the range.
822 * true if today's date is in the given date range
824 public static function getRange($startDate, $endDate) {
825 $today = date("Y-m-d");
826 $mysqlStartDate = self
::isoToMysql($startDate);
827 $mysqlEndDate = self
::isoToMysql($endDate);
828 $mysqlToday = self
::isoToMysql($today);
830 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
833 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
836 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
843 * Get start date and end from
844 * the given relative term and unit
846 * @param string $relative Relative format in the format term.unit.
849 * @param string $from
851 * @param string $fromTime
852 * @param string $toTime
855 * start date, end date
857 public static function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = '235959') {
859 list($term, $unit) = explode('.', $relative, 2);
860 $dateRange = self
::relativeToAbsolute($term, $unit);
861 $from = substr($dateRange['from'], 0, 8);
862 $to = substr($dateRange['to'], 0, 8);
863 // @todo fix relativeToAbsolute & add tests
864 // relativeToAbsolute returns 8 char date strings
865 // or 14 char date + time strings.
866 // We should use those. However, it turns out to be unreliable.
867 // e.g. this.week does NOT return 235959 for 'from'
868 // so our defaults are more reliable.
869 // Currently relativeToAbsolute only supports 'whole' days so that is ok
872 $from = self
::processDate($from, $fromTime);
873 $to = self
::processDate($to, $toTime);
879 * Calculate Age in Years if greater than one year else in months.
881 * @param date $birthDate
885 * array $results contains years or months
887 public static function calculateAge($birthDate) {
889 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
891 $bDate = explode('-', $formatedBirthDate);
892 $birthYear = $bDate[0];
893 $birthMonth = $bDate[1];
894 $birthDay = $bDate[2];
895 $year_diff = date("Y") - $birthYear;
897 // don't calculate age CRM-3143
898 if ($birthYear == '1902') {
902 switch ($year_diff) {
904 $month = (12 - $birthMonth) +
date("m");
906 if (date("d") < $birthDay) {
909 $results['months'] = $month;
911 elseif ($month == 12 && (date("d") < $birthDay)) {
912 $results['months'] = $month - 1;
915 $results['years'] = $year_diff;
920 $month = date("m") - $birthMonth;
921 $results['months'] = $month;
925 $results['years'] = $year_diff;
926 if ((date("m") < $birthMonth) ||
(date("m") == $birthMonth) && (date("d") < $birthDay)) {
935 * Calculate next payment date according to provided unit & interval
937 * @param string $unit
938 * Frequency unit like year,month, week etc.
940 * @param int $interval
941 * Frequency interval.
944 * Start date of pledge.
946 * @param bool $dontCareTime
949 * contains new date with added interval
951 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
952 if (is_array($date)) {
953 $hour = CRM_Utils_Array
::value('H', $date);
954 $minute = CRM_Utils_Array
::value('i', $date);
955 $second = CRM_Utils_Array
::value('s', $date);
956 $month = CRM_Utils_Array
::value('M', $date);
957 $day = CRM_Utils_Array
::value('d', $date);
958 $year = CRM_Utils_Array
::value('Y', $date);
961 extract(date_parse($date));
963 $date = mktime($hour, $minute, $second, $month, $day, $year);
966 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
970 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
974 $interval = $interval * 7;
975 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
979 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
983 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
987 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
990 $date['M'] = $scheduleDate[0];
991 $date['d'] = $scheduleDate[1];
992 $date['Y'] = $scheduleDate[2];
993 if ($dontCareTime == FALSE) {
994 $date['H'] = $scheduleDate[3];
995 $date['i'] = $scheduleDate[4];
996 $date['s'] = $scheduleDate[5];
1002 * Get the smarty view presentation mapping for the given format.
1004 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1005 * they should be rendered using a longer date format. This is likely as much to
1006 * do with the earlier date widget being unable to handle some formats as usablity.
1007 * However, we continue to respect this.
1010 * Given format ( eg 'M Y', 'Y M' ).
1012 * @return string|null
1013 * Smarty translation of the date format. Null is also valid and is translated
1014 * according to the available parts at the smarty layer.
1016 public static function getDateFieldViewFormat($format) {
1017 $supportableFormats = [
1018 'mm/dd' => '%B %E%f',
1019 'dd-mm' => '%E%f %B',
1023 'dd/mm/yy' => '%E%f %B %Y',
1026 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1030 * Pick the smarty format from settings that best matches the time string we have.
1032 * For view purposes we historically use the setting that most closely matches the data
1033 * in the format from our settings, as opposed to the setting configured for the field.
1038 public static function pickBestSmartyFormat($format) {
1039 if (stristr($format, 'h')) {
1040 return Civi
::settings()->get('dateformatDatetime');
1042 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1043 return Civi
::settings()->get('dateformatFull');
1045 if (stristr($format, 'm')) {
1046 return Civi
::settings()->get('dateformatPartial');
1048 return Civi
::settings()->get('dateformatYear');
1052 * Map date plugin and actual format that is used by PHP.
1056 public static function datePluginToPHPFormats() {
1057 $dateInputFormats = [
1058 "mm/dd/yy" => 'm/d/Y',
1059 "dd/mm/yy" => 'd/m/Y',
1060 "yy-mm-dd" => 'Y-m-d',
1061 "dd-mm-yy" => 'd-m-Y',
1062 "dd.mm.yy" => 'd.m.Y',
1064 "M d, yy" => 'M j, Y',
1065 "d M yy" => 'j M Y',
1066 "MM d, yy" => 'F j, Y',
1067 "d MM yy" => 'j F Y',
1068 "DD, d MM yy" => 'l, j F Y',
1076 return $dateInputFormats;
1080 * Resolves the given relative time interval into finite time limits.
1082 * @param string $relativeTerm
1083 * Relative time frame: this, previous, previous_1.
1085 * Frequency unit like year, month, week etc.
1088 * start date and end date for the relative time frame
1090 public static function relativeToAbsolute($relativeTerm, $unit) {
1092 $from = $to = $dateRange = [];
1093 $from['H'] = $from['i'] = $from['s'] = 0;
1094 $relativeTermParts = explode('_', $relativeTerm);
1095 $relativeTermPrefix = $relativeTermParts[0];
1096 $relativeTermSuffix = isset($relativeTermParts[1]) ?
$relativeTermParts[1] : '';
1100 switch ($relativeTerm) {
1102 $from['M'] = $from['d'] = 1;
1105 $to['Y'] = $from['Y'] = $now['year'] - 1;
1108 case 'previous_before':
1109 $from['M'] = $from['d'] = 1;
1112 $to['Y'] = $from['Y'] = $now['year'] - 2;
1116 $from['M'] = $from['d'] = 1;
1119 $from['Y'] = $now['year'] - 2;
1120 $to['Y'] = $now['year'] - 1;
1126 $to['Y'] = $now['year'] - 1;
1131 $from['M'] = $from['d'] = 1;
1132 $from['Y'] = $now['year'];
1136 case 'greater_previous':
1139 $from['Y'] = $now['year'] - 1;
1144 $to['d'] = $now['mday'];
1145 $to['M'] = $now['mon'];
1146 $to['Y'] = $now['year'];
1148 $to['i'] = $to['s'] = 59;
1149 $from = self
::intervalAdd('year', -1, $to);
1150 $from = self
::intervalAdd('second', 1, $from);
1154 $from['M'] = $from['d'] = 1;
1155 $from['Y'] = $now['year'];
1157 $to['i'] = $to['s'] = 59;
1158 $to['d'] = $now['mday'];
1159 $to['M'] = $now['mon'];
1160 $to['Y'] = $now['year'];
1164 $to['d'] = $now['mday'];
1165 $to['M'] = $now['mon'];
1166 $to['Y'] = $now['year'];
1168 $to['i'] = $to['s'] = 59;
1169 $from = self
::intervalAdd('year', -2, $to);
1170 $from = self
::intervalAdd('second', 1, $from);
1174 $to['d'] = $now['mday'];
1175 $to['M'] = $now['mon'];
1176 $to['Y'] = $now['year'];
1178 $to['i'] = $to['s'] = 59;
1179 $from = self
::intervalAdd('year', -3, $to);
1180 $from = self
::intervalAdd('second', 1, $from);
1186 $to['Y'] = $now['year'];
1191 $from['M'] = $from['d'] = 1;
1194 $to['Y'] = $from['Y'] = $now['year'] +
1;
1198 $from['d'] = $now['mday'];
1199 $from['M'] = $now['mon'];
1200 $from['Y'] = $now['year'];
1201 $to['d'] = $now['mday'] - 1;
1202 $to['M'] = $now['mon'];
1203 $to['Y'] = $now['year'] +
1;
1207 switch ($relativeTermPrefix) {
1210 $to['d'] = $now['mday'];
1211 $to['M'] = $now['mon'];
1212 $to['Y'] = $now['year'];
1214 $to['i'] = $to['s'] = 59;
1215 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1216 $from = self
::intervalAdd('second', 1, $from);
1220 $from['d'] = $from['M'] = 1;
1223 $to['Y'] = $from['Y'] = $now['year'];
1224 if (is_numeric($relativeTermSuffix)) {
1225 $from['Y'] -= ($relativeTermSuffix - 1);
1234 $config = CRM_Core_Config
::singleton();
1235 $from['d'] = $config->fiscalYearStart
['d'];
1236 $from['M'] = $config->fiscalYearStart
['M'];
1237 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1238 switch ($relativeTermPrefix) {
1240 $from['Y'] = $fYear;
1241 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1242 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1243 $to['d'] = $fiscalEnd['2'];
1244 $to['M'] = $fiscalEnd['1'];
1245 $to['Y'] = $fiscalEnd['0'];
1247 $to['i'] = $to['s'] = 59;
1248 if (is_numeric($relativeTermSuffix)) {
1249 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1250 $from = self
::intervalAdd('second', 1, $from);
1255 if (!is_numeric($relativeTermSuffix)) {
1256 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
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;
1266 $from['Y'] = $fYear - $relativeTermSuffix;
1267 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1268 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1269 $to['d'] = $fiscalEnd['2'];
1270 $to['M'] = $fiscalEnd['1'];
1273 $to['i'] = $to['s'] = 59;
1278 $from['Y'] = $fYear +
1;
1279 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1280 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1281 $to['d'] = $fiscalEnd['2'];
1282 $to['M'] = $fiscalEnd['1'];
1283 $to['Y'] = $fiscalEnd['0'];
1289 switch ($relativeTerm) {
1292 $quarter = ceil($now['mon'] / 3);
1294 $from['M'] = (3 * $quarter) - 2;
1295 $to['M'] = 3 * $quarter;
1296 $to['Y'] = $from['Y'] = $now['year'];
1297 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1302 $quarter = ceil($now['mon'] / 3);
1303 $quarter = $quarter - $difference;
1305 if ($quarter <= 0) {
1310 $from['M'] = (3 * $quarter) - 2;
1311 $to['M'] = 3 * $quarter;
1312 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1313 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1316 case 'previous_before':
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']));
1334 $quarter = ceil($now['mon'] / 3);
1335 $current_quarter = $quarter;
1336 $quarter = $quarter - $difference;
1338 if ($quarter <= 0) {
1343 $from['M'] = (3 * $quarter) - 2;
1344 switch ($current_quarter) {
1346 $to['M'] = (4 * $quarter);
1350 $to['M'] = (4 * $quarter) +
3;
1354 $to['M'] = (4 * $quarter) +
2;
1358 $to['M'] = (4 * $quarter) +
1;
1361 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1362 if ($to['M'] > 12) {
1363 $to['M'] = 3 * ($quarter - 3);
1364 $to['Y'] = $now['year'];
1366 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1370 $quarter = ceil($now['mon'] / 3) - 1;
1372 if ($quarter <= 0) {
1376 $to['M'] = 3 * $quarter;
1377 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1378 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1383 $quarter = ceil($now['mon'] / 3);
1385 $from['M'] = (3 * $quarter) - 2;
1386 $from['Y'] = $now['year'];
1390 case 'greater_previous':
1391 $quarter = ceil($now['mon'] / 3) - 1;
1393 if ($quarter <= 0) {
1397 $from['M'] = 3 * $quarter;
1398 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1399 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1404 $to['d'] = $now['mday'];
1405 $to['M'] = $now['mon'];
1406 $to['Y'] = $now['year'];
1408 $to['i'] = $to['s'] = 59;
1409 $from = self
::intervalAdd('day', -90, $to);
1410 $from = self
::intervalAdd('second', 1, $from);
1414 $quarter = ceil($now['mon'] / 3);
1416 $from['M'] = (3 * $quarter) - 2;
1417 $from['Y'] = $now['year'];
1418 $to['d'] = $now['mday'];
1419 $to['M'] = $now['mon'];
1420 $to['Y'] = $now['year'];
1422 $to['i'] = $to['s'] = 59;
1426 $quarter = ceil($now['mon'] / 3);
1427 $to['M'] = 3 * $quarter;
1428 $to['Y'] = $now['year'];
1429 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1436 $quarter = ceil($now['mon'] / 3);
1437 $quarter = $quarter - $difference;
1440 $now['year'] = $now['year'] +
1;
1443 if ($quarter <= 0) {
1448 $from['M'] = (3 * $quarter) - 2;
1449 $to['M'] = 3 * $quarter;
1450 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1451 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1455 $from['d'] = $now['mday'];
1456 $from['M'] = $now['mon'];
1457 $from['Y'] = $now['year'];
1459 $from['i'] = $to['s'] = 00;
1460 $to = self
::intervalAdd('day', 90, $from);
1461 $to = self
::intervalAdd('second', -1, $to);
1465 if ($relativeTermPrefix === 'ending') {
1466 $to['d'] = $now['mday'];
1467 $to['M'] = $now['mon'];
1468 $to['Y'] = $now['year'];
1470 $to['i'] = $to['s'] = 59;
1471 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1472 $from = self
::intervalAdd('second', 1, $from);
1478 switch ($relativeTerm) {
1481 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1482 $from['M'] = $to['M'] = $now['mon'];
1483 $from['Y'] = $to['Y'] = $now['year'];
1488 if ($now['mon'] == 1) {
1489 $from['M'] = $to['M'] = 12;
1490 $from['Y'] = $to['Y'] = $now['year'] - 1;
1493 $from['M'] = $to['M'] = $now['mon'] - 1;
1494 $from['Y'] = $to['Y'] = $now['year'];
1496 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1499 case 'previous_before':
1501 if ($now['mon'] < 3) {
1502 $from['M'] = $to['M'] = 10 +
$now['mon'];
1503 $from['Y'] = $to['Y'] = $now['year'] - 1;
1506 $from['M'] = $to['M'] = $now['mon'] - 2;
1507 $from['Y'] = $to['Y'] = $now['year'];
1509 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1514 if ($now['mon'] < 3) {
1515 $from['M'] = 10 +
$now['mon'];
1516 $from['Y'] = $now['year'] - 1;
1519 $from['M'] = $now['mon'] - 2;
1520 $from['Y'] = $now['year'];
1523 if ($now['mon'] == 1) {
1525 $to['Y'] = $now['year'] - 1;
1528 $to['M'] = $now['mon'] - 1;
1529 $to['Y'] = $now['year'];
1532 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1536 // before end of past month
1537 if ($now['mon'] == 1) {
1539 $to['Y'] = $now['year'] - 1;
1542 $to['M'] = $now['mon'] - 1;
1543 $to['Y'] = $now['year'];
1546 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1552 $from['M'] = $now['mon'];
1553 $from['Y'] = $now['year'];
1557 case 'greater_previous':
1558 // from end of past month
1559 if ($now['mon'] == 1) {
1561 $from['Y'] = $now['year'] - 1;
1564 $from['M'] = $now['mon'] - 1;
1565 $from['Y'] = $now['year'];
1568 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1573 $to['d'] = $now['mday'];
1574 $to['M'] = $now['mon'];
1575 $to['Y'] = $now['year'];
1577 $to['i'] = $to['s'] = 59;
1578 $from = self
::intervalAdd('day', -60, $to);
1579 $from = self
::intervalAdd('second', 1, $from);
1583 $to['d'] = $now['mday'];
1584 $to['M'] = $now['mon'];
1585 $to['Y'] = $now['year'];
1587 $to['i'] = $to['s'] = 59;
1588 $from = self
::intervalAdd('day', -30, $to);
1589 $from = self
::intervalAdd('second', 1, $from);
1594 $from['M'] = $now['mon'];
1595 $from['Y'] = $now['year'];
1596 $to['d'] = $now['mday'];
1597 $to['M'] = $now['mon'];
1598 $to['Y'] = $now['year'];
1600 $to['i'] = $to['s'] = 59;
1605 $to['Y'] = $now['year'];
1606 $to['M'] = $now['mon'];
1607 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1613 if ($now['mon'] == 12) {
1614 $from['M'] = $to['M'] = 1;
1615 $from['Y'] = $to['Y'] = $now['year'] +
1;
1618 $from['M'] = $to['M'] = $now['mon'] +
1;
1619 $from['Y'] = $to['Y'] = $now['year'];
1621 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1625 $from['d'] = $now['mday'];
1626 $from['M'] = $now['mon'];
1627 $from['Y'] = $now['year'];
1629 $from['i'] = $to['s'] = 00;
1630 $to = self
::intervalAdd('day', 30, $from);
1631 $to = self
::intervalAdd('second', -1, $to);
1635 $from['d'] = $now['mday'];
1636 $from['M'] = $now['mon'];
1637 $from['Y'] = $now['year'];
1639 $from['i'] = $to['s'] = 00;
1640 $to = self
::intervalAdd('day', 60, $from);
1641 $to = self
::intervalAdd('second', -1, $to);
1645 if ($relativeTermPrefix === 'ending') {
1646 $to['d'] = $now['mday'];
1647 $to['M'] = $now['mon'];
1648 $to['Y'] = $now['year'];
1650 $to['i'] = $to['s'] = 59;
1651 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1652 $from = self
::intervalAdd('second', 1, $from);
1658 $weekFirst = Civi
::settings()->get('weekBegins');
1659 $thisDay = $now['wday'];
1660 if ($weekFirst > $thisDay) {
1661 $diffDay = $thisDay - $weekFirst +
7;
1664 $diffDay = $thisDay - $weekFirst;
1666 switch ($relativeTerm) {
1668 $from['d'] = $now['mday'];
1669 $from['M'] = $now['mon'];
1670 $from['Y'] = $now['year'];
1671 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1672 $to = self
::intervalAdd('day', 6, $from);
1676 $from['d'] = $now['mday'];
1677 $from['M'] = $now['mon'];
1678 $from['Y'] = $now['year'];
1679 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1680 $to = self
::intervalAdd('day', 6, $from);
1683 case 'previous_before':
1684 $from['d'] = $now['mday'];
1685 $from['M'] = $now['mon'];
1686 $from['Y'] = $now['year'];
1687 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $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) - 14, $from);
1696 $to = self
::intervalAdd('day', 13, $from);
1700 $to['d'] = $now['mday'];
1701 $to['M'] = $now['mon'];
1702 $to['Y'] = $now['year'];
1703 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1708 $from['d'] = $now['mday'];
1709 $from['M'] = $now['mon'];
1710 $from['Y'] = $now['year'];
1711 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1715 case 'greater_previous':
1716 $from['d'] = $now['mday'];
1717 $from['M'] = $now['mon'];
1718 $from['Y'] = $now['year'];
1719 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1724 $to['d'] = $now['mday'];
1725 $to['M'] = $now['mon'];
1726 $to['Y'] = $now['year'];
1728 $to['i'] = $to['s'] = 59;
1729 $from = self
::intervalAdd('day', -7, $to);
1730 $from = self
::intervalAdd('second', 1, $from);
1734 $from['d'] = $now['mday'];
1735 $from['M'] = $now['mon'];
1736 $from['Y'] = $now['year'];
1737 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1738 $to['d'] = $now['mday'];
1739 $to['M'] = $now['mon'];
1740 $to['Y'] = $now['year'];
1742 $to['i'] = $to['s'] = 59;
1746 $to['d'] = $now['mday'];
1747 $to['M'] = $now['mon'];
1748 $to['Y'] = $now['year'];
1750 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1755 $from['d'] = $now['mday'];
1756 $from['M'] = $now['mon'];
1757 $from['Y'] = $now['year'];
1758 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1759 $to = self
::intervalAdd('day', 6, $from);
1763 $from['d'] = $now['mday'];
1764 $from['M'] = $now['mon'];
1765 $from['Y'] = $now['year'];
1767 $from['i'] = $to['s'] = 00;
1768 $to = self
::intervalAdd('day', 7, $from);
1769 $to = self
::intervalAdd('second', -1, $to);
1773 if ($relativeTermPrefix === 'ending') {
1774 $to['d'] = $now['mday'];
1775 $to['M'] = $now['mon'];
1776 $to['Y'] = $now['year'];
1778 $to['i'] = $to['s'] = 59;
1779 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1780 $from = self
::intervalAdd('second', 1, $from);
1786 switch ($relativeTerm) {
1788 $from['d'] = $to['d'] = $now['mday'];
1789 $from['M'] = $to['M'] = $now['mon'];
1790 $from['Y'] = $to['Y'] = $now['year'];
1794 $from['d'] = $now['mday'];
1795 $from['M'] = $now['mon'];
1796 $from['Y'] = $now['year'];
1797 $from = self
::intervalAdd('day', -1, $from);
1798 $to['d'] = $from['d'];
1799 $to['M'] = $from['M'];
1800 $to['Y'] = $from['Y'];
1803 case 'previous_before':
1804 $from['d'] = $now['mday'];
1805 $from['M'] = $now['mon'];
1806 $from['Y'] = $now['year'];
1807 $from = self
::intervalAdd('day', -2, $from);
1808 $to['d'] = $from['d'];
1809 $to['M'] = $from['M'];
1810 $to['Y'] = $from['Y'];
1814 $from['d'] = $to['d'] = $now['mday'];
1815 $from['M'] = $to['M'] = $now['mon'];
1816 $from['Y'] = $to['Y'] = $now['year'];
1817 $from = self
::intervalAdd('day', -2, $from);
1818 $to = self
::intervalAdd('day', -1, $to);
1822 $to['d'] = $now['mday'];
1823 $to['M'] = $now['mon'];
1824 $to['Y'] = $now['year'];
1829 $from['d'] = $now['mday'];
1830 $from['M'] = $now['mon'];
1831 $from['Y'] = $now['year'];
1836 $to['d'] = $now['mday'];
1837 $to['M'] = $now['mon'];
1838 $to['Y'] = $now['year'];
1839 $to = self
::intervalAdd('day', 1, $to);
1840 $from['d'] = $to['d'];
1841 $from['M'] = $to['M'];
1842 $from['Y'] = $to['Y'];
1846 if ($relativeTermPrefix === 'ending') {
1847 $to['d'] = $now['mday'];
1848 $to['M'] = $now['mon'];
1849 $to['Y'] = $now['year'];
1851 $to['i'] = $to['s'] = 59;
1852 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1853 $from = self
::intervalAdd('second', 1, $from);
1859 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1860 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1865 * Calculate current fiscal year based on the fiscal month and day.
1867 * @param int $fyDate
1868 * Fiscal start date.
1870 * @param int $fyMonth
1871 * Fiscal Start Month.
1874 * $fy Current Fiscal Year
1876 public static function calculateFiscalYear($fyDate, $fyMonth) {
1877 $date = date("Y-m-d");
1878 $currentYear = date("Y");
1880 // recalculate the date because month 4::04 make the difference
1881 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1882 $fyDate = $fiscalYear[2];
1883 $fyMonth = $fiscalYear[1];
1884 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1886 if ($fyStartDate > $date) {
1887 $fy = intval(intval($currentYear) - 1);
1890 $fy = intval($currentYear);
1896 * Function to process date, convert to mysql format
1898 * @param string $date
1900 * @param string $time
1902 * @param bool|string $returnNullString 'null' needs to be returned
1903 * so that db oject will set null in db
1904 * @param string $format
1905 * Expected return date format.( default is mysql ).
1908 * date format that is excepted by mysql
1910 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1913 if ($returnNullString) {
1914 $mysqlDate = 'null';
1918 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1925 * Add the metadata about a date field to the field.
1927 * This metadata will work with the call $form->add('datepicker', ...
1929 * @param array $fieldMetaData
1930 * @param array $field
1934 public static function addDateMetadataToField($fieldMetaData, $field) {
1935 if (isset($fieldMetaData['html'])) {
1936 $field['html_type'] = $fieldMetaData['html']['type'];
1937 if ($field['html_type'] === 'Select Date') {
1938 if (!isset($field['date_format'])) {
1939 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1940 $field['start_date_years'] = $dateAttributes['minYear'];
1941 $field['end_date_years'] = $dateAttributes['maxYear'];
1942 $field['date_format'] = $dateAttributes['format'];
1943 $field['is_datetime_field'] = TRUE;
1944 $field['time_format'] = $dateAttributes['time'];
1945 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1947 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1948 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1955 * Get the fields required for the 'extra' parameter when adding a datepicker.
1957 * @param array $field
1961 public static function getDatePickerExtra($field) {
1963 if (isset($field['date_format'])) {
1964 $extra['date'] = $field['date_format'];
1965 $extra['time'] = $field['time_format'];
1967 $thisYear = date('Y');
1968 if (isset($field['start_date_years'])) {
1969 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1971 if (isset($field['end_date_years'])) {
1972 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1978 * Get the attributes parameters required for datepicker.
1980 * @param array $field
1984 * Array ready to pass to $this->addForm('datepicker' as attributes.
1986 public static function getDatePickerAttributes(&$field) {
1989 'start_date_years' => 'minYear',
1990 'end_date_years' => 'maxYear',
1991 'date_format' => 'format',
1993 foreach ($dateAttributes as $dateAttribute => $mapTo) {
1994 if (isset($field[$dateAttribute])) {
1995 $attributes[$mapTo] = $field[$dateAttribute];
2002 * Function to convert mysql to date plugin format.
2004 * @param string $mysqlDate
2007 * @param null $formatType
2008 * @param null $format
2009 * @param null $timeFormat
2014 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2015 // if date is not passed assume it as today
2017 $mysqlDate = date('Y-m-d G:i:s');
2020 $config = CRM_Core_Config
::singleton();
2022 // get actual format
2023 $params = ['name' => $formatType];
2025 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2027 if ($values['date_format']) {
2028 $format = $values['date_format'];
2031 if (isset($values['time_format'])) {
2032 $timeFormat = $values['time_format'];
2036 // now we set display date using js, hence we should always setdefault
2037 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
2038 // note that for date display we dynamically create text field
2041 $format = $config->dateInputFormat;
2044 // get actual format
2045 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
2046 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
2049 $dateFormat = 'm/d/Y';
2050 $date = date($dateFormat, strtotime($mysqlDate));
2053 $timeFormat = $config->timeInputFormat
;
2056 $actualTimeFormat = "g:iA";
2057 $appendZeroLength = 7;
2058 if ($timeFormat > 1) {
2059 $actualTimeFormat = "G:i";
2060 $appendZeroLength = 5;
2063 $time = date($actualTimeFormat, strtotime($mysqlDate));
2065 // need to append zero for hours < 10
2066 if (strlen($time) < $appendZeroLength) {
2067 $time = '0' . $time;
2070 return [$date, $time];
2074 * Function get date format.
2076 * @param string $formatType
2077 * Date name e.g. birth.
2081 public static function getDateFormat($formatType = NULL) {
2084 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2085 $formatType, 'date_format', 'name'
2090 $config = CRM_Core_Config
::singleton();
2091 $format = $config->dateInputFormat
;
2100 * @return null|string
2102 public static function formatDate($date, $dateType) {
2103 $formattedDate = NULL;
2105 return $formattedDate;
2108 // 1. first convert date to default format.
2109 // 2. append time to default formatted date (might be removed during format)
2110 // 3. validate date / date time.
2111 // 4. If date and time then convert to default date time format.
2114 $dateParams = [$dateKey => $date];
2116 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2117 $dateVal = $dateParams[$dateKey];
2119 if ($dateType == 1) {
2121 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2122 $ruleName = 'dateTime';
2123 if (strpos($date, '-') !== FALSE) {
2124 $dateVal .= array_shift($matches);
2130 $valid = CRM_Utils_Rule
::$ruleName($dateVal);
2133 // format date and time to default.
2134 if ($ruleName == 'dateTime') {
2135 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2136 // hack to add seconds
2139 $formattedDate = $dateVal;
2143 return $formattedDate;
2147 * Function to return days of the month.
2151 public static function getCalendarDayOfMonth() {
2153 for ($i = 1; $i <= 31; $i++
) {
2156 $month[$i] = $i . ' / Last day of month';
2163 * Convert a relative date format to an api field.
2165 * @param array $params
2166 * @param string $dateField
2167 * @param bool $isDatePicker
2168 * Non datepicker fields are deprecated. Exterminate Exterminate.
2169 * (but for now handle them).
2171 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2172 if (!empty($params[$dateField . '_relative'])) {
2173 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2174 unset($params[$dateField . '_relative']);
2176 if (!empty($params[$dateField . '_low'])) {
2177 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2178 unset($params[$dateField . '_low']);
2180 if (!empty($params[$dateField . '_high'])) {
2181 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2182 unset($params[$dateField . '_high']);
2184 if (empty($dates)) {
2187 if (empty($dates[0])) {
2188 $params[$dateField] = ['<=' => $dates[1]];
2190 elseif (empty($dates[1])) {
2191 $params[$dateField] = ['>=' => $dates[0]];
2194 $params[$dateField] = ['BETWEEN' => $dates];
2199 * Print out a date object in specified format in local timezone
2201 * @param DateTimeObject $dateObject
2202 * @param string $format
2205 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2206 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2207 $dateObject->setTimezone($systemTimeZone);
2208 return $dateObject->format($format);