3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
21 class CRM_Utils_Date
{
24 * Format a date by padding it with leading '0'.
28 * @param string $separator
29 * The separator to use when formatting the date.
30 * @param int|string $invalidDate what to return if the date is invalid
33 * formatted string for date
35 public static function format($date, $separator = '', $invalidDate = 0) {
36 if (is_numeric($date) &&
37 ((strlen($date) == 8) ||
(strlen($date) == 14))
42 if (!is_array($date) ||
43 CRM_Utils_System
::isNull($date) ||
49 $date['Y'] = (int ) $date['Y'];
50 if ($date['Y'] < 1000 ||
$date['Y'] > 2999) {
54 if (array_key_exists('m', $date)) {
55 $date['M'] = $date['m'];
57 elseif (array_key_exists('F', $date)) {
58 $date['M'] = $date['F'];
61 if (!empty($date['M'])) {
62 $date['M'] = (int ) $date['M'];
63 if ($date['M'] < 1 ||
$date['M'] > 12) {
71 if (!empty($date['d'])) {
72 $date['d'] = (int ) $date['d'];
78 if (!checkdate($date['M'], $date['d'], $date['Y'])) {
82 $date['M'] = sprintf('%02d', $date['M']);
83 $date['d'] = sprintf('%02d', $date['d']);
86 if (CRM_Utils_Array
::value('H', $date) != NULL ||
87 CRM_Utils_Array
::value('h', $date) != NULL ||
88 CRM_Utils_Array
::value('i', $date) != NULL ||
89 CRM_Utils_Array
::value('s', $date) != NULL
92 if (!empty($date['h'])) {
93 if (CRM_Utils_Array
::value('A', $date) == 'PM' or CRM_Utils_Array
::value('a', $date) == 'pm') {
94 if ($date['h'] != 12) {
95 $date['h'] = $date['h'] +
12;
98 if ((CRM_Utils_Array
::value('A', $date) == 'AM' or CRM_Utils_Array
::value('a', $date) == 'am') &&
99 CRM_Utils_Array
::value('h', $date) == 12
104 $date['h'] = (int ) $date['h'];
110 // in 24-hour format the hour is under the 'H' key
111 if (!empty($date['H'])) {
112 $date['H'] = (int) $date['H'];
118 if (!empty($date['i'])) {
119 $date['i'] = (int ) $date['i'];
125 if ($date['h'] == 0 && $date['H'] != 0) {
126 $date['h'] = $date['H'];
129 if (!empty($date['s'])) {
130 $date['s'] = (int ) $date['s'];
136 $date['h'] = sprintf('%02d', $date['h']);
137 $date['i'] = sprintf('%02d', $date['i']);
138 $date['s'] = sprintf('%02d', $date['s']);
143 $time .= $date['h'] . $separator . $date['i'] . $separator . $date['s'];
146 return $date['Y'] . $separator . $date['M'] . $separator . $date['d'] . $time;
150 * Return abbreviated weekday names according to the locale.
152 * Array will be in localized order according to 'weekBegins' setting,
153 * but array keys will always match to:
159 * 0-based array with abbreviated weekday names
162 public static function getAbbrWeekdayNames() {
163 $key = 'abbrDays_' . \CRM_Core_I18n
::getLocale();
164 $days = &\Civi
::$statics[__CLASS__
][$key];
167 // First day of the week
168 $firstDay = Civi
::settings()->get('weekBegins');
170 // set LC_TIME and build the arrays from locale-provided names
171 // June 1st, 1970 was a Monday
172 CRM_Core_I18n
::setLcTime();
173 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
174 $days[$i] = strftime('%a', mktime(0, 0, 0, 6, $i, 1970));
181 * Return full weekday names according to the locale.
183 * Array will be in localized order according to 'weekBegins' setting,
184 * but array keys will always match to:
190 * 0-based array with full weekday names
193 public static function getFullWeekdayNames() {
194 $key = 'fullDays_' . \CRM_Core_I18n
::getLocale();
195 $days = &\Civi
::$statics[__CLASS__
][$key];
198 // First day of the week
199 $firstDay = Civi
::settings()->get('weekBegins');
201 // set LC_TIME and build the arrays from locale-provided names
202 // June 1st, 1970 was a Monday
203 CRM_Core_I18n
::setLcTime();
204 for ($i = $firstDay; count($days) < 7; $i = $i > 5 ?
0 : $i +
1) {
205 $days[$i] = strftime('%A', mktime(0, 0, 0, 6, $i, 1970));
212 * Return abbreviated month names according to the locale.
217 * 1-based array with abbreviated month names
220 public static function &getAbbrMonthNames($month = FALSE) {
221 $key = 'abbrMonthNames_' . \CRM_Core_I18n
::getLocale();
222 $abbrMonthNames = &\Civi
::$statics[__CLASS__
][$key];
223 if (!isset($abbrMonthNames)) {
225 // set LC_TIME and build the arrays from locale-provided names
226 CRM_Core_I18n
::setLcTime();
227 for ($i = 1; $i <= 12; $i++
) {
228 $abbrMonthNames[$i] = strftime('%b', mktime(0, 0, 0, $i, 10, 1970));
232 return $abbrMonthNames[$month];
234 return $abbrMonthNames;
238 * Return full month names according to the locale.
241 * 1-based array with full month names
244 public static function &getFullMonthNames() {
245 $key = 'fullMonthNames_' . \CRM_Core_I18n
::getLocale();
246 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
247 // Not relying on strftime because it depends on the operating system
248 // and most people will not have a non-US locale configured out of the box
249 // Ignoring other date names for now, since less visible by default
250 \Civi
::$statics[__CLASS__
][$key] = [
259 9 => ts('September'),
261 11 => ts('November'),
262 12 => ts('December'),
266 return \Civi
::$statics[__CLASS__
][$key];
270 * @param string $string
274 public static function unixTime($string) {
275 if (empty($string)) {
278 $parsedDate = date_parse($string);
279 return mktime(CRM_Utils_Array
::value('hour', $parsedDate),
280 CRM_Utils_Array
::value('minute', $parsedDate),
282 CRM_Utils_Array
::value('month', $parsedDate),
283 CRM_Utils_Array
::value('day', $parsedDate),
284 CRM_Utils_Array
::value('year', $parsedDate)
289 * Create a date and time string in a provided format.
291 * %b - abbreviated month name ('Jan'..'Dec')
292 * %B - full month name ('January'..'December')
293 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
294 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
295 * %E - day of the month as a decimal number ('1'..'31')
296 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
297 * %H - hour in 24-hour format, 0-padded ('00'..'23')
298 * %I - hour in 12-hour format, 0-padded ('01'..'12')
299 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
300 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
301 * %m - month as a decimal number, 0-padded ('01'..'12')
302 * %M - minute, 0-padded ('00'..'60')
303 * %p - lowercase ante/post meridiem ('am', 'pm')
304 * %P - uppercase ante/post meridiem ('AM', 'PM')
305 * %Y - year as a decimal number including the century ('2005')
307 * @param string $dateString
308 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
309 * @param string $format
311 * @param array $dateParts
312 * An array with the desired date parts.
315 * the $format-formatted $date
317 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
318 // 1-based (January) month names arrays
319 $abbrMonths = self
::getAbbrMonthNames();
320 $fullMonths = self
::getFullMonthNames();
323 $config = CRM_Core_Config
::singleton();
326 if (array_intersect(['h', 'H'], $dateParts)) {
327 $format = $config->dateformatDatetime
;
329 elseif (array_intersect(['d', 'j'], $dateParts)) {
330 $format = $config->dateformatFull
;
332 elseif (array_intersect(['m', 'M'], $dateParts)) {
333 $format = $config->dateformatPartial
;
336 $format = $config->dateformatYear
;
340 if (strpos(($dateString ??
''), '-')) {
341 $month = (int) substr($dateString, 5, 2);
342 $day = (int) substr($dateString, 8, 2);
345 $month = (int) substr(($dateString ??
''), 4, 2);
346 $day = (int) substr(($dateString ??
''), 6, 2);
349 if (strlen(($dateString ??
'')) > 10) {
350 $format = $config->dateformatDatetime
;
353 $format = $config->dateformatFull
;
355 elseif ($month > 0) {
356 $format = $config->dateformatPartial
;
359 $format = $config->dateformatYear
;
364 if (!CRM_Utils_System
::isNull($dateString)) {
365 if (strpos($dateString, '-')) {
366 $year = (int) substr($dateString, 0, 4);
367 $month = (int) substr($dateString, 5, 2);
368 $day = (int) substr($dateString, 8, 2);
370 $hour24 = (int) substr($dateString, 11, 2);
371 $minute = (int) substr($dateString, 14, 2);
372 $second = (int) substr($dateString, 17, 2);
375 $year = (int) substr($dateString, 0, 4);
376 $month = (int) substr($dateString, 4, 2);
377 $day = (int) substr($dateString, 6, 2);
379 $hour24 = (int) substr($dateString, 8, 2);
380 $minute = (int) substr($dateString, 10, 2);
381 $second = (int) substr($dateString, 12, 2);
384 if ($day %
10 == 1 and $day != 11) {
387 elseif ($day %
10 == 2 and $day != 12) {
390 elseif ($day %
10 == 3 and $day != 13) {
411 $hour12 = $hour24 - 12;
417 '%b' => $abbrMonths[$month] ??
NULL,
418 '%B' => $fullMonths[$month] ??
NULL,
419 '%d' => $day > 9 ?
$day : '0' . $day,
420 '%e' => $day > 9 ?
$day : ' ' . $day,
423 '%H' => $hour24 > 9 ?
$hour24 : '0' . $hour24,
424 '%h' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
425 '%I' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
426 '%k' => $hour24 > 9 ?
$hour24 : ' ' . $hour24,
427 '%l' => $hour12 > 9 ?
$hour12 : ' ' . $hour12,
428 '%m' => $month > 9 ?
$month : '0' . $month,
429 '%M' => $minute > 9 ?
$minute : '0' . $minute,
430 '%i' => $minute > 9 ?
$minute : '0' . $minute,
431 '%p' => strtolower($type),
435 '%s' => str_pad($second, 2, 0, STR_PAD_LEFT
),
436 '%S' => str_pad($second, 2, 0, STR_PAD_LEFT
),
439 return strtr($format, $date);
445 * Format the field according to the site's preferred date format.
447 * This is likely to look something like December 31st, 2020.
449 * @param string $date
453 public static function formatDateOnlyLong(string $date):string {
454 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
458 * Wrapper for customFormat that takes a timestamp
460 * @param int $timestamp
461 * Date and time in timestamp format.
462 * @param string $format
464 * @param array $dateParts
465 * An array with the desired date parts.
468 * the $format-formatted $date
470 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
471 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
475 * Converts the date/datetime from MySQL format to ISO format
477 * @param string $mysql
478 * Date/datetime in MySQL format.
481 * date/datetime in ISO format
483 public static function mysqlToIso($mysql) {
484 $year = substr(($mysql ??
''), 0, 4);
485 $month = substr(($mysql ??
''), 4, 2);
486 $day = substr(($mysql ??
''), 6, 2);
487 $hour = substr(($mysql ??
''), 8, 2);
488 $minute = substr(($mysql ??
''), 10, 2);
489 $second = substr(($mysql ??
''), 12, 2);
515 * Converts the date/datetime from ISO format to MySQL format
516 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
517 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
518 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
521 * Date/datetime in ISO format.
524 * date/datetime in MySQL format
526 public static function isoToMysql($iso) {
527 $dropArray = ['-' => '', ':' => '', ' ' => ''];
528 return strtr(($iso ??
''), $dropArray);
532 * Converts the any given date to default date format.
534 * @param array $params
535 * Has given date-format.
536 * @param int $dateType
538 * @param string $dateParam
543 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
547 if (!empty($params[$dateParam])) {
548 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
549 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
554 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
560 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
566 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
572 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
578 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
584 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
590 if ($dateType == 1) {
591 $formattedDate = explode("-", $value);
592 if (count($formattedDate) == 3) {
593 $year = (int) $formattedDate[0];
594 $month = (int) $formattedDate[1];
595 $day = (int) $formattedDate[2];
597 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
605 if ($dateType == 2 ||
$dateType == 4) {
606 $formattedDate = explode("/", $value);
607 if (count($formattedDate) != 3) {
608 $formattedDate = explode("-", $value);
610 if (count($formattedDate) == 3) {
611 $year = (int) $formattedDate[2];
612 $month = (int) $formattedDate[0];
613 $day = (int) $formattedDate[1];
619 if ($dateType == 8) {
620 $dateArray = explode(' ', $value);
622 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
625 $fullMonths = self
::getFullMonthNames();
626 foreach ($fullMonths as $key => $val) {
627 if (strtolower($dateArray[0]) == strtolower($val)) {
633 $abbrMonths = self
::getAbbrMonthNames();
634 foreach ($abbrMonths as $key => $val) {
635 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
641 $year = (int) $dateArray[2];
642 $day = (int) $dateArray[1];
643 $month = (int) $monthInt;
645 if ($dateType == 16) {
646 $dateArray = explode('-', $value);
647 if (count($dateArray) != 3) {
648 $dateArray = explode('/', $value);
651 if (count($dateArray) == 3) {
653 $fullMonths = self
::getFullMonthNames();
654 foreach ($fullMonths as $key => $val) {
655 if (strtolower($dateArray[1]) == strtolower($val)) {
661 $abbrMonths = self
::getAbbrMonthNames();
662 foreach ($abbrMonths as $key => $val) {
663 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
670 $monthInt = $dateArray[1];
673 $year = (int) $dateArray[2];
674 $day = (int) $dateArray[0];
675 $month = (int) $monthInt;
681 if ($dateType == 32) {
682 $formattedDate = explode("/", $value);
683 if (count($formattedDate) == 3) {
684 $year = (int) $formattedDate[2];
685 $month = (int) $formattedDate[1];
686 $day = (int) $formattedDate[0];
693 $month = ($month < 10) ?
"0" . "$month" : $month;
694 $day = ($day < 10) ?
"0" . "$day" : $day;
698 $year = substr($now['year'], 0, 2) * 100 +
$year;
699 if ($year > ($now['year'] +
5)) {
702 elseif ($year <= ($now['year'] - 95)) {
707 if ($params[$dateParam]) {
708 $params[$dateParam] = "$year$month$day";
710 // if month is invalid return as error
711 if ($month !== '00' && $month <= 12) {
718 * Translate a TTL to a concrete expiration time.
720 * @param null|int|DateInterval $ttl
721 * @param int $default
722 * The value to use if $ttl is not specified (NULL).
724 * Timestamp (seconds since epoch).
725 * @throws \CRM_Utils_Cache_InvalidArgumentException
727 public static function convertCacheTtlToExpires($ttl, $default) {
733 return time() +
$ttl;
735 elseif ($ttl instanceof DateInterval
) {
736 return date_add(new DateTime(), $ttl)->getTimestamp();
739 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
746 * @param null|int|DateInterval $ttl
747 * @param int $default
748 * The value to use if $ttl is not specified (NULL).
750 * Seconds until expiration.
751 * @throws \CRM_Utils_Cache_InvalidArgumentException
753 public static function convertCacheTtl($ttl, $default) {
757 elseif (is_int($ttl)) {
760 elseif ($ttl instanceof DateInterval
) {
761 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
764 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
769 * @param int|false|null $timeStamp
771 * @return bool|string
773 public static function currentDBDate($timeStamp = NULL) {
774 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
783 public static function overdue($date, $now = NULL) {
784 $mysqlDate = self
::isoToMysql($date);
786 $now = self
::currentDBDate();
789 $now = self
::isoToMysql($now);
792 return !(strtotime($mysqlDate) >= strtotime($now));
796 * Get customized today.
798 * This function is used for getting customized today. To get
799 * actuall today pass 'dayParams' as null. or else pass the day,
800 * month, year values as array values
801 * Example: $dayParams = array(
802 * 'day' => '25', 'month' => '10',
803 * 'year' => '2007' );
805 * @param array $dayParams of the day, month, year.
806 * Array of the day, month, year.
808 * @param string $format
809 * Expected date format( default.
810 * format is 2007-12-21 )
813 * Return the customized today's date (Y-m-d)
815 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
816 if (is_null($dayParams) ||
empty($dayParams)) {
817 $today = date($format);
820 $today = date($format, mktime(0, 0, 0,
831 * Find whether today's date lies in
834 * @param date $startDate
835 * Start date for the range.
836 * @param date $endDate
837 * End date for the range.
840 * true if today's date is in the given date range
842 public static function getRange($startDate, $endDate) {
843 $today = date("Y-m-d");
844 $mysqlStartDate = self
::isoToMysql($startDate);
845 $mysqlEndDate = self
::isoToMysql($endDate);
846 $mysqlToday = self
::isoToMysql($today);
848 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
851 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
854 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
861 * Get start date and end from
862 * the given relative term and unit
864 * @param string $relative Relative format in the format term.unit.
867 * @param string $from
869 * @param string $fromTime
870 * @param string $toTime
873 * start date, end date
875 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
877 list($term, $unit) = explode('.', $relative, 2);
878 $dateRange = self
::relativeToAbsolute($term, $unit);
879 $from = substr(($dateRange['from'] ??
''), 0, 8);
880 $to = substr(($dateRange['to'] ??
''), 0, 8);
881 // @todo fix relativeToAbsolute & add tests
882 // relativeToAbsolute returns 8 char date strings
883 // or 14 char date + time strings.
884 // We should use those. However, it turns out to be unreliable.
885 // e.g. this.week does NOT return 235959 for 'from'
886 // so our defaults are more reliable.
887 // Currently relativeToAbsolute only supports 'whole' days so that is ok
890 $from = self
::processDate($from, $fromTime);
891 $to = self
::processDate($to, $toTime);
897 * Calculate Age in Years if greater than one year else in months.
899 * @param date $birthDate
901 * @param date $targetDate
902 * Target Date. (show age on specific date)
905 * array $results contains years or months
907 public static function calculateAge($birthDate, $targetDate = NULL) {
909 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
911 $bDate = explode('-', $formatedBirthDate);
912 $birthYear = $bDate[0];
913 $birthMonth = $bDate[1];
914 $birthDay = $bDate[2];
915 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
917 $year_diff = date("Y", $targetDate) - $birthYear;
919 // don't calculate age CRM-3143
920 if ($birthYear == '1902') {
923 switch ($year_diff) {
925 $month = (12 - $birthMonth) +
date("m", $targetDate);
927 if (date("d", $targetDate) < $birthDay) {
930 $results['months'] = $month;
932 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
933 $results['months'] = $month - 1;
936 $results['years'] = $year_diff;
941 $month = date("m", $targetDate) - $birthMonth;
942 $results['months'] = $month;
946 $results['years'] = $year_diff;
947 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
956 * Calculate next payment date according to provided unit & interval
958 * @param string $unit
959 * Frequency unit like year,month, week etc.
961 * @param int $interval
962 * Frequency interval.
965 * Start date of pledge.
967 * @param bool $dontCareTime
970 * contains new date with added interval
972 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
973 if (is_array($date)) {
974 $hour = $date['H'] ??
'00';
975 $minute = $date['i'] ??
'00';
976 $second = $date['s'] ??
'00';
977 $month = $date['M'] ??
NULL;
978 $day = $date['d'] ??
NULL;
979 $year = $date['Y'] ??
NULL;
982 extract(date_parse($date));
984 $date = mktime($hour, $minute, $second, $month, $day, $year);
987 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
991 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
995 $interval = $interval * 7;
996 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1000 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1004 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1008 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1011 $date['M'] = $scheduleDate[0];
1012 $date['d'] = $scheduleDate[1];
1013 $date['Y'] = $scheduleDate[2];
1014 if ($dontCareTime == FALSE) {
1015 $date['H'] = $scheduleDate[3];
1016 $date['i'] = $scheduleDate[4];
1017 $date['s'] = $scheduleDate[5];
1023 * Get the smarty view presentation mapping for the given format.
1025 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1026 * they should be rendered using a longer date format. This is likely as much to
1027 * do with the earlier date widget being unable to handle some formats as usablity.
1028 * However, we continue to respect this.
1031 * Given format ( eg 'M Y', 'Y M' ).
1033 * @return string|null
1034 * Smarty translation of the date format. Null is also valid and is translated
1035 * according to the available parts at the smarty layer.
1037 public static function getDateFieldViewFormat($format) {
1038 $supportableFormats = [
1039 'mm/dd' => '%B %E%f',
1040 'dd-mm' => '%E%f %B',
1044 'dd/mm/yy' => '%E%f %B %Y',
1047 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1051 * Pick the smarty format from settings that best matches the time string we have.
1053 * For view purposes we historically use the setting that most closely matches the data
1054 * in the format from our settings, as opposed to the setting configured for the field.
1059 public static function pickBestSmartyFormat($format) {
1060 if (stristr($format, 'h')) {
1061 return Civi
::settings()->get('dateformatDatetime');
1063 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1064 return Civi
::settings()->get('dateformatFull');
1066 if (stristr($format, 'm')) {
1067 return Civi
::settings()->get('dateformatPartial');
1069 return Civi
::settings()->get('dateformatYear');
1073 * Map date plugin and actual format that is used by PHP.
1077 public static function datePluginToPHPFormats() {
1078 $dateInputFormats = [
1079 "mm/dd/yy" => 'm/d/Y',
1080 "dd/mm/yy" => 'd/m/Y',
1081 "yy-mm-dd" => 'Y-m-d',
1082 "dd-mm-yy" => 'd-m-Y',
1083 "dd.mm.yy" => 'd.m.Y',
1085 "M d, yy" => 'M j, Y',
1086 "d M yy" => 'j M Y',
1087 "MM d, yy" => 'F j, Y',
1088 "d MM yy" => 'j F Y',
1089 "DD, d MM yy" => 'l, j F Y',
1097 return $dateInputFormats;
1101 * Resolves the given relative time interval into finite time limits.
1103 * @param string $relativeTerm
1104 * Relative time frame: this, previous, previous_1.
1106 * Frequency unit like year, month, week etc.
1109 * start date and end date for the relative time frame
1111 public static function relativeToAbsolute($relativeTerm, $unit) {
1113 $from = $to = $dateRange = [];
1114 $from['H'] = $from['i'] = $from['s'] = 0;
1115 $relativeTermParts = explode('_', $relativeTerm);
1116 $relativeTermPrefix = $relativeTermParts[0];
1117 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1121 switch ($relativeTerm) {
1123 $from['M'] = $from['d'] = 1;
1126 $to['Y'] = $from['Y'] = $now['year'] - 1;
1129 case 'previous_before':
1130 $from['M'] = $from['d'] = 1;
1133 $to['Y'] = $from['Y'] = $now['year'] - 2;
1137 $from['M'] = $from['d'] = 1;
1140 $from['Y'] = $now['year'] - 2;
1141 $to['Y'] = $now['year'] - 1;
1147 $to['Y'] = $now['year'] - 1;
1152 $from['M'] = $from['d'] = 1;
1153 $from['Y'] = $now['year'];
1157 case 'greater_previous':
1160 $from['Y'] = $now['year'] - 1;
1165 $to['d'] = $now['mday'];
1166 $to['M'] = $now['mon'];
1167 $to['Y'] = $now['year'];
1169 $to['i'] = $to['s'] = 59;
1170 $from = self
::intervalAdd('year', -1, $to);
1171 $from = self
::intervalAdd('second', 1, $from);
1175 $from['M'] = $from['d'] = 1;
1176 $from['Y'] = $now['year'];
1178 $to['i'] = $to['s'] = 59;
1179 $to['d'] = $now['mday'];
1180 $to['M'] = $now['mon'];
1181 $to['Y'] = $now['year'];
1185 $to['d'] = $now['mday'];
1186 $to['M'] = $now['mon'];
1187 $to['Y'] = $now['year'];
1189 $to['i'] = $to['s'] = 59;
1190 $from = self
::intervalAdd('year', -2, $to);
1191 $from = self
::intervalAdd('second', 1, $from);
1195 $to['d'] = $now['mday'];
1196 $to['M'] = $now['mon'];
1197 $to['Y'] = $now['year'];
1199 $to['i'] = $to['s'] = 59;
1200 $from = self
::intervalAdd('year', -3, $to);
1201 $from = self
::intervalAdd('second', 1, $from);
1207 $to['Y'] = $now['year'];
1212 $from['M'] = $from['d'] = 1;
1215 $to['Y'] = $from['Y'] = $now['year'] +
1;
1219 $from['d'] = $now['mday'];
1220 $from['M'] = $now['mon'];
1221 $from['Y'] = $now['year'];
1222 $to['d'] = $now['mday'] - 1;
1223 $to['M'] = $now['mon'];
1224 $to['Y'] = $now['year'] +
1;
1228 switch ($relativeTermPrefix) {
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);
1241 $from['d'] = $from['M'] = 1;
1244 $to['Y'] = $from['Y'] = $now['year'];
1245 if (is_numeric($relativeTermSuffix)) {
1246 $from['Y'] -= ($relativeTermSuffix - 1);
1255 $config = CRM_Core_Config
::singleton();
1256 $from['d'] = $config->fiscalYearStart
['d'];
1257 $from['M'] = $config->fiscalYearStart
['M'];
1258 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1259 switch ($relativeTermPrefix) {
1261 $from['Y'] = $fYear;
1262 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1263 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1264 $to['d'] = $fiscalEnd['2'];
1265 $to['M'] = $fiscalEnd['1'];
1266 $to['Y'] = $fiscalEnd['0'];
1268 $to['i'] = $to['s'] = 59;
1269 if (is_numeric($relativeTermSuffix)) {
1270 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1271 $from = self
::intervalAdd('second', 1, $from);
1276 if (!is_numeric($relativeTermSuffix)) {
1277 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1278 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1279 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1280 $to['d'] = $fiscalEnd['2'];
1281 $to['M'] = $fiscalEnd['1'];
1282 $to['Y'] = $fiscalEnd['0'];
1284 $to['i'] = $to['s'] = 59;
1287 $from['Y'] = $fYear - $relativeTermSuffix;
1288 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1289 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1290 $to['d'] = $fiscalEnd['2'];
1291 $to['M'] = $fiscalEnd['1'];
1294 $to['i'] = $to['s'] = 59;
1299 $from['Y'] = $fYear +
1;
1300 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1301 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1302 $to['d'] = $fiscalEnd['2'];
1303 $to['M'] = $fiscalEnd['1'];
1304 $to['Y'] = $fiscalEnd['0'];
1310 switch ($relativeTerm) {
1313 $quarter = ceil($now['mon'] / 3);
1315 $from['M'] = (3 * $quarter) - 2;
1316 $to['M'] = 3 * $quarter;
1317 $to['Y'] = $from['Y'] = $now['year'];
1318 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1323 $quarter = ceil($now['mon'] / 3);
1324 $quarter = $quarter - $difference;
1326 if ($quarter <= 0) {
1331 $from['M'] = (3 * $quarter) - 2;
1332 $to['M'] = 3 * $quarter;
1333 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1334 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1337 case 'previous_before':
1339 $quarter = ceil($now['mon'] / 3);
1340 $quarter = $quarter - $difference;
1342 if ($quarter <= 0) {
1347 $from['M'] = (3 * $quarter) - 2;
1348 $to['M'] = 3 * $quarter;
1349 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1350 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1355 $quarter = ceil($now['mon'] / 3);
1356 $current_quarter = $quarter;
1357 $quarter = $quarter - $difference;
1359 if ($quarter <= 0) {
1364 $from['M'] = (3 * $quarter) - 2;
1365 switch ($current_quarter) {
1367 $to['M'] = (4 * $quarter);
1371 $to['M'] = (4 * $quarter) +
3;
1375 $to['M'] = (4 * $quarter) +
2;
1379 $to['M'] = (4 * $quarter) +
1;
1382 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1383 if ($to['M'] > 12) {
1384 $to['M'] = 3 * ($quarter - 3);
1385 $to['Y'] = $now['year'];
1387 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1391 $quarter = ceil($now['mon'] / 3) - 1;
1393 if ($quarter <= 0) {
1397 $to['M'] = 3 * $quarter;
1398 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1399 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1404 $quarter = ceil($now['mon'] / 3);
1406 $from['M'] = (3 * $quarter) - 2;
1407 $from['Y'] = $now['year'];
1411 case 'greater_previous':
1412 $quarter = ceil($now['mon'] / 3) - 1;
1414 if ($quarter <= 0) {
1418 $from['M'] = 3 * $quarter;
1419 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1420 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1425 $to['d'] = $now['mday'];
1426 $to['M'] = $now['mon'];
1427 $to['Y'] = $now['year'];
1429 $to['i'] = $to['s'] = 59;
1430 $from = self
::intervalAdd('day', -90, $to);
1431 $from = self
::intervalAdd('second', 1, $from);
1435 $quarter = ceil($now['mon'] / 3);
1437 $from['M'] = (3 * $quarter) - 2;
1438 $from['Y'] = $now['year'];
1439 $to['d'] = $now['mday'];
1440 $to['M'] = $now['mon'];
1441 $to['Y'] = $now['year'];
1443 $to['i'] = $to['s'] = 59;
1447 $quarter = ceil($now['mon'] / 3);
1448 $to['M'] = 3 * $quarter;
1449 $to['Y'] = $now['year'];
1450 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1457 $quarter = ceil($now['mon'] / 3);
1458 $quarter = $quarter - $difference;
1461 $now['year'] = $now['year'] +
1;
1464 if ($quarter <= 0) {
1469 $from['M'] = (3 * $quarter) - 2;
1470 $to['M'] = 3 * $quarter;
1471 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1472 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1476 $from['d'] = $now['mday'];
1477 $from['M'] = $now['mon'];
1478 $from['Y'] = $now['year'];
1480 $from['i'] = $to['s'] = 00;
1481 $to = self
::intervalAdd('day', 90, $from);
1482 $to = self
::intervalAdd('second', -1, $to);
1486 if ($relativeTermPrefix === 'ending') {
1487 $to['d'] = $now['mday'];
1488 $to['M'] = $now['mon'];
1489 $to['Y'] = $now['year'];
1491 $to['i'] = $to['s'] = 59;
1492 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1493 $from = self
::intervalAdd('second', 1, $from);
1499 switch ($relativeTerm) {
1502 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1503 $from['M'] = $to['M'] = $now['mon'];
1504 $from['Y'] = $to['Y'] = $now['year'];
1509 if ($now['mon'] == 1) {
1510 $from['M'] = $to['M'] = 12;
1511 $from['Y'] = $to['Y'] = $now['year'] - 1;
1514 $from['M'] = $to['M'] = $now['mon'] - 1;
1515 $from['Y'] = $to['Y'] = $now['year'];
1517 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1520 case 'previous_before':
1522 if ($now['mon'] < 3) {
1523 $from['M'] = $to['M'] = 10 +
$now['mon'];
1524 $from['Y'] = $to['Y'] = $now['year'] - 1;
1527 $from['M'] = $to['M'] = $now['mon'] - 2;
1528 $from['Y'] = $to['Y'] = $now['year'];
1530 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1535 if ($now['mon'] < 3) {
1536 $from['M'] = 10 +
$now['mon'];
1537 $from['Y'] = $now['year'] - 1;
1540 $from['M'] = $now['mon'] - 2;
1541 $from['Y'] = $now['year'];
1544 if ($now['mon'] == 1) {
1546 $to['Y'] = $now['year'] - 1;
1549 $to['M'] = $now['mon'] - 1;
1550 $to['Y'] = $now['year'];
1553 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1557 // before end of past month
1558 if ($now['mon'] == 1) {
1560 $to['Y'] = $now['year'] - 1;
1563 $to['M'] = $now['mon'] - 1;
1564 $to['Y'] = $now['year'];
1567 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1573 $from['M'] = $now['mon'];
1574 $from['Y'] = $now['year'];
1578 case 'greater_previous':
1579 // from end of past month
1580 if ($now['mon'] == 1) {
1582 $from['Y'] = $now['year'] - 1;
1585 $from['M'] = $now['mon'] - 1;
1586 $from['Y'] = $now['year'];
1589 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1594 $to['d'] = $now['mday'];
1595 $to['M'] = $now['mon'];
1596 $to['Y'] = $now['year'];
1598 $to['i'] = $to['s'] = 59;
1599 $from = self
::intervalAdd('day', -60, $to);
1600 $from = self
::intervalAdd('second', 1, $from);
1604 $to['d'] = $now['mday'];
1605 $to['M'] = $now['mon'];
1606 $to['Y'] = $now['year'];
1608 $to['i'] = $to['s'] = 59;
1609 $from = self
::intervalAdd('day', -30, $to);
1610 $from = self
::intervalAdd('second', 1, $from);
1615 $from['M'] = $now['mon'];
1616 $from['Y'] = $now['year'];
1617 $to['d'] = $now['mday'];
1618 $to['M'] = $now['mon'];
1619 $to['Y'] = $now['year'];
1621 $to['i'] = $to['s'] = 59;
1626 $to['Y'] = $now['year'];
1627 $to['M'] = $now['mon'];
1628 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1634 if ($now['mon'] == 12) {
1635 $from['M'] = $to['M'] = 1;
1636 $from['Y'] = $to['Y'] = $now['year'] +
1;
1639 $from['M'] = $to['M'] = $now['mon'] +
1;
1640 $from['Y'] = $to['Y'] = $now['year'];
1642 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1646 $from['d'] = $now['mday'];
1647 $from['M'] = $now['mon'];
1648 $from['Y'] = $now['year'];
1650 $from['i'] = $to['s'] = 00;
1651 $to = self
::intervalAdd('day', 30, $from);
1652 $to = self
::intervalAdd('second', -1, $to);
1656 $from['d'] = $now['mday'];
1657 $from['M'] = $now['mon'];
1658 $from['Y'] = $now['year'];
1660 $from['i'] = $to['s'] = 00;
1661 $to = self
::intervalAdd('day', 60, $from);
1662 $to = self
::intervalAdd('second', -1, $to);
1666 if ($relativeTermPrefix === 'ending') {
1667 $to['d'] = $now['mday'];
1668 $to['M'] = $now['mon'];
1669 $to['Y'] = $now['year'];
1671 $to['i'] = $to['s'] = 59;
1672 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1673 $from = self
::intervalAdd('second', 1, $from);
1679 $weekFirst = Civi
::settings()->get('weekBegins');
1680 $thisDay = $now['wday'];
1681 if ($weekFirst > $thisDay) {
1682 $diffDay = $thisDay - $weekFirst +
7;
1685 $diffDay = $thisDay - $weekFirst;
1687 switch ($relativeTerm) {
1689 $from['d'] = $now['mday'];
1690 $from['M'] = $now['mon'];
1691 $from['Y'] = $now['year'];
1692 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1693 $to = self
::intervalAdd('day', 6, $from);
1697 $from['d'] = $now['mday'];
1698 $from['M'] = $now['mon'];
1699 $from['Y'] = $now['year'];
1700 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1701 $to = self
::intervalAdd('day', 6, $from);
1704 case 'previous_before':
1705 $from['d'] = $now['mday'];
1706 $from['M'] = $now['mon'];
1707 $from['Y'] = $now['year'];
1708 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1709 $to = self
::intervalAdd('day', 6, $from);
1713 $from['d'] = $now['mday'];
1714 $from['M'] = $now['mon'];
1715 $from['Y'] = $now['year'];
1716 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1717 $to = self
::intervalAdd('day', 13, $from);
1721 $to['d'] = $now['mday'];
1722 $to['M'] = $now['mon'];
1723 $to['Y'] = $now['year'];
1724 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1729 $from['d'] = $now['mday'];
1730 $from['M'] = $now['mon'];
1731 $from['Y'] = $now['year'];
1732 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1736 case 'greater_previous':
1737 $from['d'] = $now['mday'];
1738 $from['M'] = $now['mon'];
1739 $from['Y'] = $now['year'];
1740 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1745 $to['d'] = $now['mday'];
1746 $to['M'] = $now['mon'];
1747 $to['Y'] = $now['year'];
1749 $to['i'] = $to['s'] = 59;
1750 $from = self
::intervalAdd('day', -7, $to);
1751 $from = self
::intervalAdd('second', 1, $from);
1755 $from['d'] = $now['mday'];
1756 $from['M'] = $now['mon'];
1757 $from['Y'] = $now['year'];
1758 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1759 $to['d'] = $now['mday'];
1760 $to['M'] = $now['mon'];
1761 $to['Y'] = $now['year'];
1763 $to['i'] = $to['s'] = 59;
1767 $to['d'] = $now['mday'];
1768 $to['M'] = $now['mon'];
1769 $to['Y'] = $now['year'];
1771 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1776 $from['d'] = $now['mday'];
1777 $from['M'] = $now['mon'];
1778 $from['Y'] = $now['year'];
1779 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1780 $to = self
::intervalAdd('day', 6, $from);
1784 $from['d'] = $now['mday'];
1785 $from['M'] = $now['mon'];
1786 $from['Y'] = $now['year'];
1788 $from['i'] = $to['s'] = 00;
1789 $to = self
::intervalAdd('day', 7, $from);
1790 $to = self
::intervalAdd('second', -1, $to);
1794 if ($relativeTermPrefix === 'ending') {
1795 $to['d'] = $now['mday'];
1796 $to['M'] = $now['mon'];
1797 $to['Y'] = $now['year'];
1799 $to['i'] = $to['s'] = 59;
1800 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1801 $from = self
::intervalAdd('second', 1, $from);
1807 switch ($relativeTerm) {
1809 $from['d'] = $to['d'] = $now['mday'];
1810 $from['M'] = $to['M'] = $now['mon'];
1811 $from['Y'] = $to['Y'] = $now['year'];
1815 $from['d'] = $now['mday'];
1816 $from['M'] = $now['mon'];
1817 $from['Y'] = $now['year'];
1818 $from = self
::intervalAdd('day', -1, $from);
1819 $to['d'] = $from['d'];
1820 $to['M'] = $from['M'];
1821 $to['Y'] = $from['Y'];
1824 case 'previous_before':
1825 $from['d'] = $now['mday'];
1826 $from['M'] = $now['mon'];
1827 $from['Y'] = $now['year'];
1828 $from = self
::intervalAdd('day', -2, $from);
1829 $to['d'] = $from['d'];
1830 $to['M'] = $from['M'];
1831 $to['Y'] = $from['Y'];
1835 $from['d'] = $to['d'] = $now['mday'];
1836 $from['M'] = $to['M'] = $now['mon'];
1837 $from['Y'] = $to['Y'] = $now['year'];
1838 $from = self
::intervalAdd('day', -2, $from);
1839 $to = self
::intervalAdd('day', -1, $to);
1843 $to['d'] = $now['mday'];
1844 $to['M'] = $now['mon'];
1845 $to['Y'] = $now['year'];
1846 $to = self
::intervalAdd('day', -1, $to);
1851 $from['d'] = $now['mday'];
1852 $from['M'] = $now['mon'];
1853 $from['Y'] = $now['year'];
1858 $to['d'] = $now['mday'];
1859 $to['M'] = $now['mon'];
1860 $to['Y'] = $now['year'];
1861 $to = self
::intervalAdd('day', 1, $to);
1862 $from['d'] = $to['d'];
1863 $from['M'] = $to['M'];
1864 $from['Y'] = $to['Y'];
1868 if ($relativeTermPrefix === 'ending') {
1869 $to['d'] = $now['mday'];
1870 $to['M'] = $now['mon'];
1871 $to['Y'] = $now['year'];
1873 $to['i'] = $to['s'] = 59;
1874 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1875 $from = self
::intervalAdd('second', 1, $from);
1881 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1882 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1887 * Calculate current fiscal year based on the fiscal month and day.
1889 * @param int $fyDate
1890 * Fiscal start date.
1892 * @param int $fyMonth
1893 * Fiscal Start Month.
1896 * $fy Current Fiscal Year
1898 public static function calculateFiscalYear($fyDate, $fyMonth) {
1899 $date = date("Y-m-d");
1900 $currentYear = date("Y");
1902 // recalculate the date because month 4::04 make the difference
1903 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1904 $fyDate = $fiscalYear[2];
1905 $fyMonth = $fiscalYear[1];
1906 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1908 if ($fyStartDate > $date) {
1909 $fy = intval(intval($currentYear) - 1);
1912 $fy = intval($currentYear);
1918 * Function to process date, convert to mysql format
1920 * @param string $date
1922 * @param string $time
1924 * @param bool|string $returnNullString 'null' needs to be returned
1925 * so that db oject will set null in db
1926 * @param string $format
1927 * Expected return date format.( default is mysql ).
1930 * date format that is excepted by mysql
1932 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1935 if ($returnNullString) {
1936 $mysqlDate = 'null';
1939 if (trim($date ??
'')) {
1940 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1947 * Add the metadata about a date field to the field.
1949 * This metadata will work with the call $form->add('datepicker', ...
1951 * @param array $fieldMetaData
1952 * @param array $field
1956 public static function addDateMetadataToField($fieldMetaData, $field) {
1957 if (isset($fieldMetaData['html'])) {
1958 $field['html_type'] = $fieldMetaData['html']['type'];
1959 if ($field['html_type'] === 'Select Date') {
1960 if (!isset($field['date_format'])) {
1961 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1962 $field['start_date_years'] = $dateAttributes['minYear'];
1963 $field['end_date_years'] = $dateAttributes['maxYear'];
1964 $field['date_format'] = $dateAttributes['format'];
1965 $field['is_datetime_field'] = TRUE;
1966 $field['time_format'] = $dateAttributes['time'];
1967 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1969 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1970 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1977 * Get the fields required for the 'extra' parameter when adding a datepicker.
1979 * @param array $field
1983 public static function getDatePickerExtra($field) {
1985 if (isset($field['date_format'])) {
1986 $extra['date'] = $field['date_format'];
1987 $extra['time'] = $field['time_format'];
1989 $thisYear = date('Y');
1990 if (isset($field['start_date_years'])) {
1991 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1993 if (isset($field['end_date_years'])) {
1994 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
2000 * Get the attributes parameters required for datepicker.
2002 * @param array $field
2006 * Array ready to pass to $this->addForm('datepicker' as attributes.
2008 public static function getDatePickerAttributes(&$field) {
2011 'start_date_years' => 'minYear',
2012 'end_date_years' => 'maxYear',
2013 'date_format' => 'format',
2015 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2016 if (isset($field[$dateAttribute])) {
2017 $attributes[$mapTo] = $field[$dateAttribute];
2024 * Function to convert mysql to date plugin format.
2026 * @param string $mysqlDate
2029 * @param null $formatType
2030 * @param null $format
2031 * @param null $timeFormat
2036 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2037 // if date is not passed assume it as today
2039 $mysqlDate = date('Y-m-d G:i:s');
2042 $config = CRM_Core_Config
::singleton();
2044 // get actual format
2045 $params = ['name' => $formatType];
2047 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2049 if ($values['date_format']) {
2050 $format = $values['date_format'];
2053 if (isset($values['time_format'])) {
2054 $timeFormat = $values['time_format'];
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
;
2106 * Date formatting for imports where date format is specified.
2108 * Note this is used for imports (only) because the importer can
2109 * specify the format.
2111 * Tests are in CRM_Utils_DateTest::testFormatDate
2114 * Date string as entered.
2116 * One of the constants like CRM_Core_Form_Date::DATE_yyyy_mm_dd.
2118 * @return null|string
2120 public static function formatDate($date, $dateType) {
2125 // 1. first convert date to default format.
2126 // 2. append time to default formatted date (might be removed during format)
2127 // 3. validate date / date time.
2128 // 4. If date and time then convert to default date time format.
2131 $dateParams = [$dateKey => $date];
2133 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2134 $dateVal = $dateParams[$dateKey];
2135 if ($dateType == 1) {
2137 // The seconds part of this regex is not quite right - but it does succeed
2138 // in clarifying whether there is a time component or not - which is all it is meant
2140 if (preg_match('/(\s(([01]\d)|[2][0-3]):([0-5]\d):?[0-5]?\d?)$/', $date, $matches)) {
2141 if (strpos($date, '-') !== FALSE) {
2142 $dateVal .= array_shift($matches);
2144 if (!CRM_Utils_Rule
::dateTime($dateVal)) {
2147 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", '', $dateVal), '%Y%m%d%H%i%s');
2153 return CRM_Utils_Rule
::date($dateVal) ?
$dateVal : NULL;
2160 * Function to return days of the month.
2164 public static function getCalendarDayOfMonth() {
2166 for ($i = 1; $i <= 31; $i++
) {
2169 $month[$i] = $i . ' / Last day of month';
2176 * Convert a relative date format to an api field.
2178 * @param array $params
2179 * @param string $dateField
2180 * @param bool $isDatePicker
2181 * Non datepicker fields are deprecated. Exterminate Exterminate.
2182 * (but for now handle them).
2184 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2185 if (!empty($params[$dateField . '_relative'])) {
2186 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2187 unset($params[$dateField . '_relative']);
2189 if (!empty($params[$dateField . '_low'])) {
2190 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2191 unset($params[$dateField . '_low']);
2193 if (!empty($params[$dateField . '_high'])) {
2194 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2195 unset($params[$dateField . '_high']);
2197 if (empty($dates)) {
2200 if (empty($dates[0])) {
2201 $params[$dateField] = ['<=' => $dates[1]];
2203 elseif (empty($dates[1])) {
2204 $params[$dateField] = ['>=' => $dates[0]];
2207 $params[$dateField] = ['BETWEEN' => $dates];
2212 * Print out a date object in specified format in local timezone
2214 * @param DateTimeObject $dateObject
2215 * @param string $format
2218 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2219 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2220 $dateObject->setTimezone($systemTimeZone);
2221 return $dateObject->format($format);
2225 * Check if the value returned by a date picker has a date section (ie: includes
2226 * a '-' character) if it includes a time section (ie: includes a ':').
2228 * @param string $value
2229 * A date/time string input from a datepicker value.
2232 * TRUE if valid, FALSE if there is a time without a date.
2234 public static function datePickerValueWithTimeHasDate($value) {
2235 // If there's no : (time) or a : and a - (date) then return true
2237 strpos($value, ':') === FALSE
2238 ||
strpos($value, ':') !== FALSE && strpos($value, '-') !== FALSE
2243 * Validate start and end dates entered on a form to make sure they are
2244 * logical. Expects the form keys to be start_date and end_date.
2246 * @param string $startFormKey
2247 * The form element key of the 'start date'
2248 * @param string $startValue
2249 * The value of the 'start date'
2250 * @param string $endFormKey
2251 * The form element key of the 'end date'
2252 * @param string $endValue
2253 * The value of the 'end date'
2255 * @return array|bool
2256 * TRUE if valid, an array of the erroneous form key, and error message to
2259 public static function validateStartEndDatepickerInputs($startFormKey, $startValue, $endFormKey, $endValue) {
2261 // Check date as well as time is set
2262 if (!empty($startValue) && !self
::datePickerValueWithTimeHasDate($startValue)) {
2263 return ['key' => $startFormKey, 'message' => ts('Please enter a date as well as a time.')];
2265 if (!empty($endValue) && !self
::datePickerValueWithTimeHasDate($endValue)) {
2266 return ['key' => $endFormKey, 'message' => ts('Please enter a date as well as a time.')];
2269 // Check end date is after start date
2270 if (!empty($startValue) && !empty($endValue) && $endValue < $startValue) {
2271 return ['key' => $endFormKey, 'message' => ts('The end date should be after the start date.')];