3 +--------------------------------------------------------------------+
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2019
37 class CRM_Utils_Date
{
40 * Format a date by padding it with leading '0'.
44 * @param string $separator
45 * The seperator to use when formatting the date.
46 * @param int|string $invalidDate what to return if the date is invalid
49 * formatted string for date
51 public static function format($date, $separator = '', $invalidDate = 0) {
52 if (is_numeric($date) &&
53 ((strlen($date) == 8) ||
(strlen($date) == 14))
58 if (!is_array($date) ||
59 CRM_Utils_System
::isNull($date) ||
65 $date['Y'] = (int ) $date['Y'];
66 if ($date['Y'] < 1000 ||
$date['Y'] > 2999) {
70 if (array_key_exists('m', $date)) {
71 $date['M'] = $date['m'];
73 elseif (array_key_exists('F', $date)) {
74 $date['M'] = $date['F'];
77 if (!empty($date['M'])) {
78 $date['M'] = (int ) $date['M'];
79 if ($date['M'] < 1 ||
$date['M'] > 12) {
87 if (!empty($date['d'])) {
88 $date['d'] = (int ) $date['d'];
94 if (!checkdate($date['M'], $date['d'], $date['Y'])) {
98 $date['M'] = sprintf('%02d', $date['M']);
99 $date['d'] = sprintf('%02d', $date['d']);
102 if (CRM_Utils_Array
::value('H', $date) != NULL ||
103 CRM_Utils_Array
::value('h', $date) != NULL ||
104 CRM_Utils_Array
::value('i', $date) != NULL ||
105 CRM_Utils_Array
::value('s', $date) != NULL
107 // we have time too..
108 if (!empty($date['h'])) {
109 if (CRM_Utils_Array
::value('A', $date) == 'PM' or CRM_Utils_Array
::value('a', $date) == 'pm') {
110 if ($date['h'] != 12) {
111 $date['h'] = $date['h'] +
12;
114 if ((CRM_Utils_Array
::value('A', $date) == 'AM' or CRM_Utils_Array
::value('a', $date) == 'am') &&
115 CRM_Utils_Array
::value('h', $date) == 12
120 $date['h'] = (int ) $date['h'];
126 // in 24-hour format the hour is under the 'H' key
127 if (!empty($date['H'])) {
128 $date['H'] = (int) $date['H'];
134 if (!empty($date['i'])) {
135 $date['i'] = (int ) $date['i'];
141 if ($date['h'] == 0 && $date['H'] != 0) {
142 $date['h'] = $date['H'];
145 if (!empty($date['s'])) {
146 $date['s'] = (int ) $date['s'];
152 $date['h'] = sprintf('%02d', $date['h']);
153 $date['i'] = sprintf('%02d', $date['i']);
154 $date['s'] = sprintf('%02d', $date['s']);
159 $time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
162 return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
166 * Return abbreviated weekday names according to the locale.
168 * Array will be in localized order according to 'weekBegins' setting,
169 * but array keys will always match to:
175 * 0-based array with abbreviated weekday names
178 public static function getAbbrWeekdayNames() {
181 // First day of the week
182 $firstDay = Civi
::settings()->get('weekBegins');
184 // set LC_TIME and build the arrays from locale-provided names
185 // June 1st, 1970 was a Monday
186 CRM_Core_I18n
::setLcTime();
187 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
188 $days[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
195 * Return full weekday names according to the locale.
197 * Array will be in localized order according to 'weekBegins' setting,
198 * but array keys will always match to:
204 * 0-based array with full weekday names
207 public static function getFullWeekdayNames() {
210 // First day of the week
211 $firstDay = Civi
::settings()->get('weekBegins');
213 // set LC_TIME and build the arrays from locale-provided names
214 // June 1st, 1970 was a Monday
215 CRM_Core_I18n
::setLcTime();
216 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
217 $days[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
224 * Return abbreviated month names according to the locale.
229 * 1-based array with abbreviated month names
232 public static function &getAbbrMonthNames($month = FALSE) {
233 static $abbrMonthNames;
234 if (!isset($abbrMonthNames)) {
236 // set LC_TIME and build the arrays from locale-provided names
237 CRM_Core_I18n
::setLcTime();
238 for ($i = 1; $i <= 12; $i++
) {
239 $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
243 return $abbrMonthNames[$month];
245 return $abbrMonthNames;
249 * Return full month names according to the locale.
252 * 1-based array with full month names
255 public static function &getFullMonthNames() {
256 static $fullMonthNames;
257 if (!isset($fullMonthNames)) {
259 // set LC_TIME and build the arrays from locale-provided names
260 CRM_Core_I18n
::setLcTime();
261 for ($i = 1; $i <= 12; $i++
) {
262 $fullMonthNames[$i] = strftime('%B', mktime(0, 0, 0, $i, 10, 1970));
265 return $fullMonthNames;
273 public static function unixTime($string) {
274 if (empty($string)) {
277 $parsedDate = date_parse($string);
278 return mktime(CRM_Utils_Array
::value('hour', $parsedDate),
279 CRM_Utils_Array
::value('minute', $parsedDate),
281 CRM_Utils_Array
::value('month', $parsedDate),
282 CRM_Utils_Array
::value('day', $parsedDate),
283 CRM_Utils_Array
::value('year', $parsedDate)
288 * Create a date and time string in a provided format.
290 * %b - abbreviated month name ('Jan'..'Dec')
291 * %B - full month name ('January'..'December')
292 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
293 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
294 * %E - day of the month as a decimal number ('1'..'31')
295 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
296 * %H - hour in 24-hour format, 0-padded ('00'..'23')
297 * %I - hour in 12-hour format, 0-padded ('01'..'12')
298 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
299 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
300 * %m - month as a decimal number, 0-padded ('01'..'12')
301 * %M - minute, 0-padded ('00'..'60')
302 * %p - lowercase ante/post meridiem ('am', 'pm')
303 * %P - uppercase ante/post meridiem ('AM', 'PM')
304 * %Y - year as a decimal number including the century ('2005')
306 * @param string $dateString
307 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
308 * @param string $format
310 * @param array $dateParts
311 * An array with the desired date parts.
314 * the $format-formatted $date
316 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
317 // 1-based (January) month names arrays
318 $abbrMonths = self
::getAbbrMonthNames();
319 $fullMonths = self
::getFullMonthNames();
322 $config = CRM_Core_Config
::singleton();
325 if (array_intersect(['h', 'H'], $dateParts)) {
326 $format = $config->dateformatDatetime
;
328 elseif (array_intersect(['d', 'j'], $dateParts)) {
329 $format = $config->dateformatFull
;
331 elseif (array_intersect(['m', 'M'], $dateParts)) {
332 $format = $config->dateformatPartial
;
335 $format = $config->dateformatYear
;
339 if (strpos($dateString, '-')) {
340 $month = (int) substr($dateString, 5, 2);
341 $day = (int) substr($dateString, 8, 2);
344 $month = (int) substr($dateString, 4, 2);
345 $day = (int) substr($dateString, 6, 2);
348 if (strlen($dateString) > 10) {
349 $format = $config->dateformatDatetime
;
352 $format = $config->dateformatFull
;
354 elseif ($month > 0) {
355 $format = $config->dateformatPartial
;
358 $format = $config->dateformatYear
;
363 if (!CRM_Utils_System
::isNull($dateString)) {
364 if (strpos($dateString, '-')) {
365 $year = (int) substr($dateString, 0, 4);
366 $month = (int) substr($dateString, 5, 2);
367 $day = (int) substr($dateString, 8, 2);
369 $hour24 = (int) substr($dateString, 11, 2);
370 $minute = (int) substr($dateString, 14, 2);
373 $year = (int) substr($dateString, 0, 4);
374 $month = (int) substr($dateString, 4, 2);
375 $day = (int) substr($dateString, 6, 2);
377 $hour24 = (int) substr($dateString, 8, 2);
378 $minute = (int) substr($dateString, 10, 2);
381 if ($day %
10 == 1 and $day != 11) {
384 elseif ($day %
10 == 2 and $day != 12) {
387 elseif ($day %
10 == 3 and $day != 13) {
408 $hour12 = $hour24 - 12;
414 '%b' => CRM_Utils_Array
::value($month, $abbrMonths),
415 '%B' => CRM_Utils_Array
::value($month, $fullMonths),
416 '%d' => $day > 9 ?
$day : '0' . $day,
417 '%e' => $day > 9 ?
$day : ' ' . $day,
420 '%H' => $hour24 > 9 ?
$hour24 : '0' . $hour24,
421 '%h' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
422 '%I' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
423 '%k' => $hour24 > 9 ?
$hour24 : ' ' . $hour24,
424 '%l' => $hour12 > 9 ?
$hour12 : ' ' . $hour12,
425 '%m' => $month > 9 ?
$month : '0' . $month,
426 '%M' => $minute > 9 ?
$minute : '0' . $minute,
427 '%i' => $minute > 9 ?
$minute : '0' . $minute,
428 '%p' => strtolower($type),
434 return strtr($format, $date);
442 * Wrapper for customFormat that takes a timestamp
444 * @param int $timestamp
445 * Date and time in timestamp format.
446 * @param string $format
448 * @param array $dateParts
449 * An array with the desired date parts.
452 * the $format-formatted $date
454 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
455 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
459 * Converts the date/datetime from MySQL format to ISO format
461 * @param string $mysql
462 * Date/datetime in MySQL format.
465 * date/datetime in ISO format
467 public static function mysqlToIso($mysql) {
468 $year = substr($mysql, 0, 4);
469 $month = substr($mysql, 4, 2);
470 $day = substr($mysql, 6, 2);
471 $hour = substr($mysql, 8, 2);
472 $minute = substr($mysql, 10, 2);
473 $second = substr($mysql, 12, 2);
499 * Converts the date/datetime from ISO format to MySQL format
500 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
501 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
502 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
505 * Date/datetime in ISO format.
508 * date/datetime in MySQL format
510 public static function isoToMysql($iso) {
511 $dropArray = ['-' => '', ':' => '', ' ' => ''];
512 return strtr($iso, $dropArray);
516 * Converts the any given date to default date format.
518 * @param array $params
519 * Has given date-format.
520 * @param int $dateType
522 * @param string $dateParam
527 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
529 $cen = substr($now['year'], 0, 2);
533 if (!empty($params[$dateParam])) {
534 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
535 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
540 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
546 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
552 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
558 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
564 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
570 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
576 if ($dateType == 1) {
577 $formattedDate = explode("-", $value);
578 if (count($formattedDate) == 3) {
579 $year = (int) $formattedDate[0];
580 $month = (int) $formattedDate[1];
581 $day = (int) $formattedDate[2];
583 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
591 if ($dateType == 2 ||
$dateType == 4) {
592 $formattedDate = explode("/", $value);
593 if (count($formattedDate) != 3) {
594 $formattedDate = explode("-", $value);
596 if (count($formattedDate) == 3) {
597 $year = (int) $formattedDate[2];
598 $month = (int) $formattedDate[0];
599 $day = (int) $formattedDate[1];
605 if ($dateType == 8) {
606 $dateArray = explode(' ', $value);
608 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
611 $fullMonths = self
::getFullMonthNames();
612 foreach ($fullMonths as $key => $val) {
613 if (strtolower($dateArray[0]) == strtolower($val)) {
619 $abbrMonths = self
::getAbbrMonthNames();
620 foreach ($abbrMonths as $key => $val) {
621 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
627 $year = (int) $dateArray[2];
628 $day = (int) $dateArray[1];
629 $month = (int) $monthInt;
631 if ($dateType == 16) {
632 $dateArray = explode('-', $value);
633 if (count($dateArray) != 3) {
634 $dateArray = explode('/', $value);
637 if (count($dateArray) == 3) {
639 $fullMonths = self
::getFullMonthNames();
640 foreach ($fullMonths as $key => $val) {
641 if (strtolower($dateArray[1]) == strtolower($val)) {
647 $abbrMonths = self
::getAbbrMonthNames();
648 foreach ($abbrMonths as $key => $val) {
649 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
656 $monthInt = $dateArray[1];
659 $year = (int) $dateArray[2];
660 $day = (int) $dateArray[0];
661 $month = (int) $monthInt;
667 if ($dateType == 32) {
668 $formattedDate = explode("/", $value);
669 if (count($formattedDate) == 3) {
670 $year = (int) $formattedDate[2];
671 $month = (int) $formattedDate[1];
672 $day = (int) $formattedDate[0];
679 $month = ($month < 10) ?
"0" . "$month" : $month;
680 $day = ($day < 10) ?
"0" . "$day" : $day;
682 $year = (int ) $year;
683 // simple heuristic to determine what century to use
684 // 00 - 20 is always 2000 - 2020
685 // 21 - 99 is always 1921 - 1999
687 $year = (strlen($year) == 1) ?
$cen . '0' . $year : $cen . $year;
689 elseif ($year < 100) {
690 $year = $prevCen . $year;
693 if ($params[$dateParam]) {
694 $params[$dateParam] = "$year$month$day";
696 // if month is invalid return as error
697 if ($month !== '00' && $month <= 12) {
708 public static function isDate(&$date) {
709 if (CRM_Utils_System
::isNull($date)) {
716 * Translate a TTL to a concrete expiration time.
718 * @param NULL|int|DateInterval $ttl
719 * @param int $default
720 * The value to use if $ttl is not specified (NULL).
722 * Timestamp (seconds since epoch).
723 * @throws \CRM_Utils_Cache_InvalidArgumentException
725 public static function convertCacheTtlToExpires($ttl, $default) {
731 return time() +
$ttl;
733 elseif ($ttl instanceof DateInterval
) {
734 return date_add(new DateTime(), $ttl)->getTimestamp();
737 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
744 * @param NULL|int|DateInterval $ttl
745 * @param int $default
746 * The value to use if $ttl is not specified (NULL).
748 * Seconds until expiration.
749 * @throws \CRM_Utils_Cache_InvalidArgumentException
751 public static function convertCacheTtl($ttl, $default) {
755 elseif (is_int($ttl)) {
758 elseif ($ttl instanceof DateInterval
) {
759 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
762 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
767 * @param null $timeStamp
769 * @return bool|string
771 public static function currentDBDate($timeStamp = NULL) {
772 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
781 public static function overdue($date, $now = NULL) {
782 $mysqlDate = self
::isoToMysql($date);
784 $now = self
::currentDBDate();
787 $now = self
::isoToMysql($now);
790 return (strtotime($mysqlDate) >= strtotime($now)) ?
FALSE : TRUE;
794 * Get customized today.
796 * This function is used for getting customized today. To get
797 * actuall today pass 'dayParams' as null. or else pass the day,
798 * month, year values as array values
799 * Example: $dayParams = array(
800 * 'day' => '25', 'month' => '10',
801 * 'year' => '2007' );
803 * @param array $dayParams of the day, month, year.
804 * Array of the day, month, year.
806 * @param string $format
807 * Expected date format( default.
808 * format is 2007-12-21 )
811 * Return the customized today's date (Y-m-d)
813 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
814 if (is_null($dayParams) ||
empty($dayParams)) {
815 $today = date($format);
818 $today = date($format, mktime(0, 0, 0,
829 * Find whether today's date lies in
832 * @param date $startDate
833 * Start date for the range.
834 * @param date $endDate
835 * End date for the range.
838 * true if today's date is in the given date range
840 public static function getRange($startDate, $endDate) {
841 $today = date("Y-m-d");
842 $mysqlStartDate = self
::isoToMysql($startDate);
843 $mysqlEndDate = self
::isoToMysql($endDate);
844 $mysqlToday = self
::isoToMysql($today);
846 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
849 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
852 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
859 * Get start date and end from
860 * the given relative term and unit
862 * @param string $relative Relative format in the format term.unit.
865 * @param string $from
867 * @param string $fromTime
868 * @param string $toTime
871 * start date, end date
873 public static function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = '235959') {
875 list($term, $unit) = explode('.', $relative, 2);
876 $dateRange = self
::relativeToAbsolute($term, $unit);
877 $from = substr($dateRange['from'], 0, 8);
878 $to = substr($dateRange['to'], 0, 8);
879 // @todo fix relativeToAbsolute & add tests
880 // relativeToAbsolute returns 8 char date strings
881 // or 14 char date + time strings.
882 // We should use those. However, it turns out to be unreliable.
883 // e.g. this.week does NOT return 235959 for 'from'
884 // so our defaults are more reliable.
885 // Currently relativeToAbsolute only supports 'whole' days so that is ok
888 $from = self
::processDate($from, $fromTime);
889 $to = self
::processDate($to, $toTime);
895 * Calculate Age in Years if greater than one year else in months.
897 * @param date $birthDate
901 * array $results contains years or months
903 public static function calculateAge($birthDate) {
905 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
907 $bDate = explode('-', $formatedBirthDate);
908 $birthYear = $bDate[0];
909 $birthMonth = $bDate[1];
910 $birthDay = $bDate[2];
911 $year_diff = date("Y") - $birthYear;
913 // don't calculate age CRM-3143
914 if ($birthYear == '1902') {
918 switch ($year_diff) {
920 $month = (12 - $birthMonth) +
date("m");
922 if (date("d") < $birthDay) {
925 $results['months'] = $month;
927 elseif ($month == 12 && (date("d") < $birthDay)) {
928 $results['months'] = $month - 1;
931 $results['years'] = $year_diff;
936 $month = date("m") - $birthMonth;
937 $results['months'] = $month;
941 $results['years'] = $year_diff;
942 if ((date("m") < $birthMonth) ||
(date("m") == $birthMonth) && (date("d") < $birthDay)) {
951 * Calculate next payment date according to provided unit & interval
953 * @param string $unit
954 * Frequency unit like year,month, week etc.
956 * @param int $interval
957 * Frequency interval.
960 * Start date of pledge.
962 * @param bool $dontCareTime
965 * contains new date with added interval
967 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
968 if (is_array($date)) {
969 $hour = CRM_Utils_Array
::value('H', $date);
970 $minute = CRM_Utils_Array
::value('i', $date);
971 $second = CRM_Utils_Array
::value('s', $date);
972 $month = CRM_Utils_Array
::value('M', $date);
973 $day = CRM_Utils_Array
::value('d', $date);
974 $year = CRM_Utils_Array
::value('Y', $date);
977 extract(date_parse($date));
979 $date = mktime($hour, $minute, $second, $month, $day, $year);
982 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
986 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
990 $interval = $interval * 7;
991 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
995 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
999 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1003 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1006 $date['M'] = $scheduleDate[0];
1007 $date['d'] = $scheduleDate[1];
1008 $date['Y'] = $scheduleDate[2];
1009 if ($dontCareTime == FALSE) {
1010 $date['H'] = $scheduleDate[3];
1011 $date['i'] = $scheduleDate[4];
1012 $date['s'] = $scheduleDate[5];
1018 * Get the smarty view presentation mapping for the given format.
1020 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1021 * they should be rendered using a longer date format. This is likely as much to
1022 * do with the earlier date widget being unable to handle some formats as usablity.
1023 * However, we continue to respect this.
1026 * Given format ( eg 'M Y', 'Y M' ).
1028 * @return string|null
1029 * Smarty translation of the date format. Null is also valid and is translated
1030 * according to the available parts at the smarty layer.
1032 public static function getDateFieldViewFormat($format) {
1033 $supportableFormats = [
1034 'mm/dd' => '%B %E%f',
1035 'dd-mm' => '%E%f %B',
1039 'dd/mm/yy' => '%E%f %B %Y',
1042 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1046 * Pick the smarty format from settings that best matches the time string we have.
1048 * For view purposes we historically use the setting that most closely matches the data
1049 * in the format from our settings, as opposed to the setting configured for the field.
1054 public static function pickBestSmartyFormat($format) {
1055 if (stristr($format, 'h')) {
1056 return Civi
::settings()->get('dateformatDatetime');
1058 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1059 return Civi
::settings()->get('dateformatFull');
1061 if (stristr($format, 'm')) {
1062 return Civi
::settings()->get('dateformatPartial');
1064 return Civi
::settings()->get('dateformatYear');
1068 * Map date plugin and actual format that is used by PHP.
1072 public static function datePluginToPHPFormats() {
1073 $dateInputFormats = [
1074 "mm/dd/yy" => 'm/d/Y',
1075 "dd/mm/yy" => 'd/m/Y',
1076 "yy-mm-dd" => 'Y-m-d',
1077 "dd-mm-yy" => 'd-m-Y',
1078 "dd.mm.yy" => 'd.m.Y',
1080 "M d, yy" => 'M j, Y',
1081 "d M yy" => 'j M Y',
1082 "MM d, yy" => 'F j, Y',
1083 "d MM yy" => 'j F Y',
1084 "DD, d MM yy" => 'l, j F Y',
1092 return $dateInputFormats;
1096 * Resolves the given relative time interval into finite time limits.
1098 * @param string $relativeTerm
1099 * Relative time frame: this, previous, previous_1.
1101 * Frequency unit like year, month, week etc.
1104 * start date and end date for the relative time frame
1106 public static function relativeToAbsolute($relativeTerm, $unit) {
1108 $from = $to = $dateRange = [];
1109 $from['H'] = $from['i'] = $from['s'] = 0;
1110 $relativeTermParts = explode('_', $relativeTerm);
1111 $relativeTermPrefix = $relativeTermParts[0];
1112 $relativeTermSuffix = isset($relativeTermParts[1]) ?
$relativeTermParts[1] : '';
1116 switch ($relativeTerm) {
1118 $from['d'] = $from['M'] = 1;
1121 $to['Y'] = $from['Y'] = $now['year'];
1125 $from['M'] = $from['d'] = 1;
1128 $to['Y'] = $from['Y'] = $now['year'] - 1;
1131 case 'previous_before':
1132 $from['M'] = $from['d'] = 1;
1135 $to['Y'] = $from['Y'] = $now['year'] - 2;
1139 $from['M'] = $from['d'] = 1;
1142 $from['Y'] = $now['year'] - 2;
1143 $to['Y'] = $now['year'] - 1;
1149 $to['Y'] = $now['year'] - 1;
1154 $from['M'] = $from['d'] = 1;
1155 $from['Y'] = $now['year'];
1159 case 'greater_previous':
1162 $from['Y'] = $now['year'] - 1;
1167 $to['d'] = $now['mday'];
1168 $to['M'] = $now['mon'];
1169 $to['Y'] = $now['year'];
1171 $to['i'] = $to['s'] = 59;
1172 $from = self
::intervalAdd('year', -1, $to);
1173 $from = self
::intervalAdd('second', 1, $from);
1177 $from['M'] = $from['d'] = 1;
1178 $from['Y'] = $now['year'];
1180 $to['i'] = $to['s'] = 59;
1181 $to['d'] = $now['mday'];
1182 $to['M'] = $now['mon'];
1183 $to['Y'] = $now['year'];
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', -2, $to);
1193 $from = self
::intervalAdd('second', 1, $from);
1197 $to['d'] = $now['mday'];
1198 $to['M'] = $now['mon'];
1199 $to['Y'] = $now['year'];
1201 $to['i'] = $to['s'] = 59;
1202 $from = self
::intervalAdd('year', -3, $to);
1203 $from = self
::intervalAdd('second', 1, $from);
1209 $to['Y'] = $now['year'];
1214 $from['M'] = $from['d'] = 1;
1217 $to['Y'] = $from['Y'] = $now['year'] +
1;
1221 $from['d'] = $now['mday'];
1222 $from['M'] = $now['mon'];
1223 $from['Y'] = $now['year'];
1224 $to['d'] = $now['mday'] - 1;
1225 $to['M'] = $now['mon'];
1226 $to['Y'] = $now['year'] +
1;
1230 if ($relativeTermPrefix === 'ending') {
1231 $to['d'] = $now['mday'];
1232 $to['M'] = $now['mon'];
1233 $to['Y'] = $now['year'];
1235 $to['i'] = $to['s'] = 59;
1236 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1237 $from = self
::intervalAdd('second', 1, $from);
1243 $config = CRM_Core_Config
::singleton();
1244 $from['d'] = $config->fiscalYearStart
['d'];
1245 $from['M'] = $config->fiscalYearStart
['M'];
1246 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1247 switch ($relativeTermPrefix) {
1249 $from['Y'] = $fYear;
1250 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1251 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1253 $to['d'] = $fiscalEnd['2'];
1254 $to['M'] = $fiscalEnd['1'];
1255 $to['Y'] = $fiscalEnd['0'];
1259 if (!is_numeric($relativeTermSuffix)) {
1260 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1261 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1262 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1263 $to['d'] = $fiscalEnd['2'];
1264 $to['M'] = $fiscalEnd['1'];
1265 $to['Y'] = $fiscalEnd['0'];
1268 $from['Y'] = $fYear - $relativeTermSuffix;
1269 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1270 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1271 $to['d'] = $fiscalEnd['2'];
1272 $to['M'] = $fiscalEnd['1'];
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);
1863 if (!empty($
$item)) {
1864 $dateRange[$item] = self
::format($
$item);
1867 $dateRange[$item] = NULL;
1874 * Calculate current fiscal year based on the fiscal month and day.
1876 * @param int $fyDate
1877 * Fiscal start date.
1879 * @param int $fyMonth
1880 * Fiscal Start Month.
1883 * $fy Current Fiscal Year
1885 public static function calculateFiscalYear($fyDate, $fyMonth) {
1886 $date = date("Y-m-d");
1887 $currentYear = date("Y");
1889 // recalculate the date because month 4::04 make the difference
1890 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1891 $fyDate = $fiscalYear[2];
1892 $fyMonth = $fiscalYear[1];
1893 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1895 if ($fyStartDate > $date) {
1896 $fy = intval(intval($currentYear) - 1);
1899 $fy = intval($currentYear);
1905 * Function to process date, convert to mysql format
1907 * @param string $date
1909 * @param string $time
1911 * @param bool|string $returnNullString 'null' needs to be returned
1912 * so that db oject will set null in db
1913 * @param string $format
1914 * Expected return date format.( default is mysql ).
1917 * date format that is excepted by mysql
1919 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1922 if ($returnNullString) {
1923 $mysqlDate = 'null';
1927 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1934 * Add the metadata about a date field to the field.
1936 * This metadata will work with the call $form->add('datepicker', ...
1938 * @param array $fieldMetaData
1939 * @param array $field
1943 public static function addDateMetadataToField($fieldMetaData, $field) {
1944 if (isset($fieldMetaData['html'])) {
1945 $field['html_type'] = $fieldMetaData['html']['type'];
1946 if ($field['html_type'] === 'Select Date') {
1947 if (!isset($field['date_format'])) {
1948 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1949 $field['start_date_years'] = $dateAttributes['minYear'];
1950 $field['end_date_years'] = $dateAttributes['maxYear'];
1951 $field['date_format'] = $dateAttributes['format'];
1952 $field['is_datetime_field'] = TRUE;
1953 $field['time_format'] = $dateAttributes['time'];
1954 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1956 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1957 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1964 * Get the fields required for the 'extra' parameter when adding a datepicker.
1966 * @param array $field
1970 public static function getDatePickerExtra($field) {
1972 if (isset($field['date_format'])) {
1973 $extra['date'] = $field['date_format'];
1974 $extra['time'] = $field['time_format'];
1976 $thisYear = date('Y');
1977 if (isset($field['start_date_years'])) {
1978 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1980 if (isset($field['end_date_years'])) {
1981 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1987 * Get the attributes parameters required for datepicker.
1989 * @param array $field
1993 * Array ready to pass to $this->addForm('datepicker' as attributes.
1995 public static function getDatePickerAttributes(&$field) {
1998 'start_date_years' => 'minYear',
1999 'end_date_years' => 'maxYear',
2000 'date_format' => 'format',
2002 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2003 if (isset($field[$dateAttribute])) {
2004 $attributes[$mapTo] = $field[$dateAttribute];
2011 * Function to convert mysql to date plugin format.
2013 * @param string $mysqlDate
2016 * @param null $formatType
2017 * @param null $format
2018 * @param null $timeFormat
2023 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2024 // if date is not passed assume it as today
2026 $mysqlDate = date('Y-m-d G:i:s');
2029 $config = CRM_Core_Config
::singleton();
2031 // get actual format
2032 $params = ['name' => $formatType];
2034 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2036 if ($values['date_format']) {
2037 $format = $values['date_format'];
2040 if (isset($values['time_format'])) {
2041 $timeFormat = $values['time_format'];
2045 // now we set display date using js, hence we should always setdefault
2046 // 'm/d/Y' format. So that submitted value is alwats mm/dd/YY format
2047 // note that for date display we dynamically create text field
2050 $format = $config->dateInputFormat;
2053 // get actual format
2054 $actualPHPFormats = CRM_Core_SelectValues::datePluginToPHPFormats( );
2055 $dateFormat = CRM_Utils_Array::value( $format, $actualPHPFormats );
2058 $dateFormat = 'm/d/Y';
2059 $date = date($dateFormat, strtotime($mysqlDate));
2062 $timeFormat = $config->timeInputFormat
;
2065 $actualTimeFormat = "g:iA";
2066 $appendZeroLength = 7;
2067 if ($timeFormat > 1) {
2068 $actualTimeFormat = "G:i";
2069 $appendZeroLength = 5;
2072 $time = date($actualTimeFormat, strtotime($mysqlDate));
2074 // need to append zero for hours < 10
2075 if (strlen($time) < $appendZeroLength) {
2076 $time = '0' . $time;
2079 return [$date, $time];
2083 * Function get date format.
2085 * @param string $formatType
2086 * Date name e.g. birth.
2090 public static function getDateFormat($formatType = NULL) {
2093 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2094 $formatType, 'date_format', 'name'
2099 $config = CRM_Core_Config
::singleton();
2100 $format = $config->dateInputFormat
;
2109 * @return null|string
2111 public static function formatDate($date, $dateType) {
2112 $formattedDate = NULL;
2114 return $formattedDate;
2117 // 1. first convert date to default format.
2118 // 2. append time to default formatted date (might be removed during format)
2119 // 3. validate date / date time.
2120 // 4. If date and time then convert to default date time format.
2123 $dateParams = [$dateKey => $date];
2125 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2126 $dateVal = $dateParams[$dateKey];
2128 if ($dateType == 1) {
2130 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2131 $ruleName = 'dateTime';
2132 if (strpos($date, '-') !== FALSE) {
2133 $dateVal .= array_shift($matches);
2139 $valid = CRM_Utils_Rule
::$ruleName($dateVal);
2142 // format date and time to default.
2143 if ($ruleName == 'dateTime') {
2144 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2145 // hack to add seconds
2148 $formattedDate = $dateVal;
2152 return $formattedDate;
2156 * Function to return days of the month.
2160 public static function getCalendarDayOfMonth() {
2162 for ($i = 1; $i <= 31; $i++
) {
2165 $month[$i] = $i . ' / Last day of month';
2172 * Convert a relative date format to an api field.
2174 * @param array $params
2175 * @param string $dateField
2176 * @param bool $isDatePicker
2177 * Non datepicker fields are deprecated. Exterminate Exterminate.
2178 * (but for now handle them).
2180 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2181 if (!empty($params[$dateField . '_relative'])) {
2182 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2183 unset($params[$dateField . '_relative']);
2185 if (!empty($params[$dateField . '_low'])) {
2186 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2187 unset($params[$dateField . '_low']);
2189 if (!empty($params[$dateField . '_high'])) {
2190 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2191 unset($params[$dateField . '_high']);
2193 if (empty($dates)) {
2196 if (empty($dates[0])) {
2197 $params[$dateField] = ['<=' => $dates[1]];
2199 elseif (empty($dates[1])) {
2200 $params[$dateField] = ['>=' => $dates[0]];
2203 $params[$dateField] = ['BETWEEN' => $dates];
2208 * Print out a date object in specified format in local timezone
2210 * @param DateTimeObject $dateObject
2211 * @param string $format
2214 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2215 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2216 $dateObject->setTimezone($systemTimeZone);
2217 return $dateObject->format($format);