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
),
438 return strtr($format, $date);
444 * Format the field according to the site's preferred date format.
446 * This is likely to look something like December 31st, 2020.
448 * @param string $date
452 public static function formatDateOnlyLong(string $date):string {
453 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
457 * Wrapper for customFormat that takes a timestamp
459 * @param int $timestamp
460 * Date and time in timestamp format.
461 * @param string $format
463 * @param array $dateParts
464 * An array with the desired date parts.
467 * the $format-formatted $date
469 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
470 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
474 * Converts the date/datetime from MySQL format to ISO format
476 * @param string $mysql
477 * Date/datetime in MySQL format.
480 * date/datetime in ISO format
482 public static function mysqlToIso($mysql) {
483 $year = substr($mysql, 0, 4);
484 $month = substr($mysql, 4, 2);
485 $day = substr($mysql, 6, 2);
486 $hour = substr($mysql, 8, 2);
487 $minute = substr($mysql, 10, 2);
488 $second = substr($mysql, 12, 2);
514 * Converts the date/datetime from ISO format to MySQL format
515 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
516 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
517 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
520 * Date/datetime in ISO format.
523 * date/datetime in MySQL format
525 public static function isoToMysql($iso) {
526 $dropArray = ['-' => '', ':' => '', ' ' => ''];
527 return strtr($iso, $dropArray);
531 * Converts the any given date to default date format.
533 * @param array $params
534 * Has given date-format.
535 * @param int $dateType
537 * @param string $dateParam
542 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
546 if (!empty($params[$dateParam])) {
547 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
548 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
553 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
559 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
565 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
571 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
577 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
583 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
589 if ($dateType == 1) {
590 $formattedDate = explode("-", $value);
591 if (count($formattedDate) == 3) {
592 $year = (int) $formattedDate[0];
593 $month = (int) $formattedDate[1];
594 $day = (int) $formattedDate[2];
596 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
604 if ($dateType == 2 ||
$dateType == 4) {
605 $formattedDate = explode("/", $value);
606 if (count($formattedDate) != 3) {
607 $formattedDate = explode("-", $value);
609 if (count($formattedDate) == 3) {
610 $year = (int) $formattedDate[2];
611 $month = (int) $formattedDate[0];
612 $day = (int) $formattedDate[1];
618 if ($dateType == 8) {
619 $dateArray = explode(' ', $value);
621 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
624 $fullMonths = self
::getFullMonthNames();
625 foreach ($fullMonths as $key => $val) {
626 if (strtolower($dateArray[0]) == strtolower($val)) {
632 $abbrMonths = self
::getAbbrMonthNames();
633 foreach ($abbrMonths as $key => $val) {
634 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
640 $year = (int) $dateArray[2];
641 $day = (int) $dateArray[1];
642 $month = (int) $monthInt;
644 if ($dateType == 16) {
645 $dateArray = explode('-', $value);
646 if (count($dateArray) != 3) {
647 $dateArray = explode('/', $value);
650 if (count($dateArray) == 3) {
652 $fullMonths = self
::getFullMonthNames();
653 foreach ($fullMonths as $key => $val) {
654 if (strtolower($dateArray[1]) == strtolower($val)) {
660 $abbrMonths = self
::getAbbrMonthNames();
661 foreach ($abbrMonths as $key => $val) {
662 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
669 $monthInt = $dateArray[1];
672 $year = (int) $dateArray[2];
673 $day = (int) $dateArray[0];
674 $month = (int) $monthInt;
680 if ($dateType == 32) {
681 $formattedDate = explode("/", $value);
682 if (count($formattedDate) == 3) {
683 $year = (int) $formattedDate[2];
684 $month = (int) $formattedDate[1];
685 $day = (int) $formattedDate[0];
692 $month = ($month < 10) ?
"0" . "$month" : $month;
693 $day = ($day < 10) ?
"0" . "$day" : $day;
697 $year = substr($now['year'], 0, 2) * 100 +
$year;
698 if ($year > ($now['year'] +
5)) {
701 elseif ($year <= ($now['year'] - 95)) {
706 if ($params[$dateParam]) {
707 $params[$dateParam] = "$year$month$day";
709 // if month is invalid return as error
710 if ($month !== '00' && $month <= 12) {
717 * Translate a TTL to a concrete expiration time.
719 * @param null|int|DateInterval $ttl
720 * @param int $default
721 * The value to use if $ttl is not specified (NULL).
723 * Timestamp (seconds since epoch).
724 * @throws \CRM_Utils_Cache_InvalidArgumentException
726 public static function convertCacheTtlToExpires($ttl, $default) {
732 return time() +
$ttl;
734 elseif ($ttl instanceof DateInterval
) {
735 return date_add(new DateTime(), $ttl)->getTimestamp();
738 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
745 * @param null|int|DateInterval $ttl
746 * @param int $default
747 * The value to use if $ttl is not specified (NULL).
749 * Seconds until expiration.
750 * @throws \CRM_Utils_Cache_InvalidArgumentException
752 public static function convertCacheTtl($ttl, $default) {
756 elseif (is_int($ttl)) {
759 elseif ($ttl instanceof DateInterval
) {
760 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
763 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
768 * @param int|false|null $timeStamp
770 * @return bool|string
772 public static function currentDBDate($timeStamp = NULL) {
773 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
782 public static function overdue($date, $now = NULL) {
783 $mysqlDate = self
::isoToMysql($date);
785 $now = self
::currentDBDate();
788 $now = self
::isoToMysql($now);
791 return !(strtotime($mysqlDate) >= strtotime($now));
795 * Get customized today.
797 * This function is used for getting customized today. To get
798 * actuall today pass 'dayParams' as null. or else pass the day,
799 * month, year values as array values
800 * Example: $dayParams = array(
801 * 'day' => '25', 'month' => '10',
802 * 'year' => '2007' );
804 * @param array $dayParams of the day, month, year.
805 * Array of the day, month, year.
807 * @param string $format
808 * Expected date format( default.
809 * format is 2007-12-21 )
812 * Return the customized today's date (Y-m-d)
814 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
815 if (is_null($dayParams) ||
empty($dayParams)) {
816 $today = date($format);
819 $today = date($format, mktime(0, 0, 0,
830 * Find whether today's date lies in
833 * @param date $startDate
834 * Start date for the range.
835 * @param date $endDate
836 * End date for the range.
839 * true if today's date is in the given date range
841 public static function getRange($startDate, $endDate) {
842 $today = date("Y-m-d");
843 $mysqlStartDate = self
::isoToMysql($startDate);
844 $mysqlEndDate = self
::isoToMysql($endDate);
845 $mysqlToday = self
::isoToMysql($today);
847 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
850 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
853 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
860 * Get start date and end from
861 * the given relative term and unit
863 * @param string $relative Relative format in the format term.unit.
866 * @param string $from
868 * @param string $fromTime
869 * @param string $toTime
872 * start date, end date
874 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
876 list($term, $unit) = explode('.', $relative, 2);
877 $dateRange = self
::relativeToAbsolute($term, $unit);
878 $from = substr($dateRange['from'], 0, 8);
879 $to = substr($dateRange['to'], 0, 8);
880 // @todo fix relativeToAbsolute & add tests
881 // relativeToAbsolute returns 8 char date strings
882 // or 14 char date + time strings.
883 // We should use those. However, it turns out to be unreliable.
884 // e.g. this.week does NOT return 235959 for 'from'
885 // so our defaults are more reliable.
886 // Currently relativeToAbsolute only supports 'whole' days so that is ok
889 $from = self
::processDate($from, $fromTime);
890 $to = self
::processDate($to, $toTime);
896 * Calculate Age in Years if greater than one year else in months.
898 * @param date $birthDate
900 * @param date $targetDate
901 * Target Date. (show age on specific date)
904 * array $results contains years or months
906 public static function calculateAge($birthDate, $targetDate = NULL) {
908 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
910 $bDate = explode('-', $formatedBirthDate);
911 $birthYear = $bDate[0];
912 $birthMonth = $bDate[1];
913 $birthDay = $bDate[2];
914 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
916 $year_diff = date("Y", $targetDate) - $birthYear;
918 // don't calculate age CRM-3143
919 if ($birthYear == '1902') {
922 switch ($year_diff) {
924 $month = (12 - $birthMonth) +
date("m", $targetDate);
926 if (date("d", $targetDate) < $birthDay) {
929 $results['months'] = $month;
931 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
932 $results['months'] = $month - 1;
935 $results['years'] = $year_diff;
940 $month = date("m", $targetDate) - $birthMonth;
941 $results['months'] = $month;
945 $results['years'] = $year_diff;
946 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
955 * Calculate next payment date according to provided unit & interval
957 * @param string $unit
958 * Frequency unit like year,month, week etc.
960 * @param int $interval
961 * Frequency interval.
964 * Start date of pledge.
966 * @param bool $dontCareTime
969 * contains new date with added interval
971 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
972 if (is_array($date)) {
973 $hour = $date['H'] ??
'00';
974 $minute = $date['i'] ??
'00';
975 $second = $date['s'] ??
'00';
976 $month = $date['M'] ??
NULL;
977 $day = $date['d'] ??
NULL;
978 $year = $date['Y'] ??
NULL;
981 extract(date_parse($date));
983 $date = mktime($hour, $minute, $second, $month, $day, $year);
986 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
990 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
994 $interval = $interval * 7;
995 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
999 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1003 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1007 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1010 $date['M'] = $scheduleDate[0];
1011 $date['d'] = $scheduleDate[1];
1012 $date['Y'] = $scheduleDate[2];
1013 if ($dontCareTime == FALSE) {
1014 $date['H'] = $scheduleDate[3];
1015 $date['i'] = $scheduleDate[4];
1016 $date['s'] = $scheduleDate[5];
1022 * Get the smarty view presentation mapping for the given format.
1024 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1025 * they should be rendered using a longer date format. This is likely as much to
1026 * do with the earlier date widget being unable to handle some formats as usablity.
1027 * However, we continue to respect this.
1030 * Given format ( eg 'M Y', 'Y M' ).
1032 * @return string|null
1033 * Smarty translation of the date format. Null is also valid and is translated
1034 * according to the available parts at the smarty layer.
1036 public static function getDateFieldViewFormat($format) {
1037 $supportableFormats = [
1038 'mm/dd' => '%B %E%f',
1039 'dd-mm' => '%E%f %B',
1043 'dd/mm/yy' => '%E%f %B %Y',
1046 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1050 * Pick the smarty format from settings that best matches the time string we have.
1052 * For view purposes we historically use the setting that most closely matches the data
1053 * in the format from our settings, as opposed to the setting configured for the field.
1058 public static function pickBestSmartyFormat($format) {
1059 if (stristr($format, 'h')) {
1060 return Civi
::settings()->get('dateformatDatetime');
1062 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1063 return Civi
::settings()->get('dateformatFull');
1065 if (stristr($format, 'm')) {
1066 return Civi
::settings()->get('dateformatPartial');
1068 return Civi
::settings()->get('dateformatYear');
1072 * Map date plugin and actual format that is used by PHP.
1076 public static function datePluginToPHPFormats() {
1077 $dateInputFormats = [
1078 "mm/dd/yy" => 'm/d/Y',
1079 "dd/mm/yy" => 'd/m/Y',
1080 "yy-mm-dd" => 'Y-m-d',
1081 "dd-mm-yy" => 'd-m-Y',
1082 "dd.mm.yy" => 'd.m.Y',
1084 "M d, yy" => 'M j, Y',
1085 "d M yy" => 'j M Y',
1086 "MM d, yy" => 'F j, Y',
1087 "d MM yy" => 'j F Y',
1088 "DD, d MM yy" => 'l, j F Y',
1096 return $dateInputFormats;
1100 * Resolves the given relative time interval into finite time limits.
1102 * @param string $relativeTerm
1103 * Relative time frame: this, previous, previous_1.
1105 * Frequency unit like year, month, week etc.
1108 * start date and end date for the relative time frame
1110 public static function relativeToAbsolute($relativeTerm, $unit) {
1112 $from = $to = $dateRange = [];
1113 $from['H'] = $from['i'] = $from['s'] = 0;
1114 $relativeTermParts = explode('_', $relativeTerm);
1115 $relativeTermPrefix = $relativeTermParts[0];
1116 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1120 switch ($relativeTerm) {
1122 $from['M'] = $from['d'] = 1;
1125 $to['Y'] = $from['Y'] = $now['year'] - 1;
1128 case 'previous_before':
1129 $from['M'] = $from['d'] = 1;
1132 $to['Y'] = $from['Y'] = $now['year'] - 2;
1136 $from['M'] = $from['d'] = 1;
1139 $from['Y'] = $now['year'] - 2;
1140 $to['Y'] = $now['year'] - 1;
1146 $to['Y'] = $now['year'] - 1;
1151 $from['M'] = $from['d'] = 1;
1152 $from['Y'] = $now['year'];
1156 case 'greater_previous':
1159 $from['Y'] = $now['year'] - 1;
1164 $to['d'] = $now['mday'];
1165 $to['M'] = $now['mon'];
1166 $to['Y'] = $now['year'];
1168 $to['i'] = $to['s'] = 59;
1169 $from = self
::intervalAdd('year', -1, $to);
1170 $from = self
::intervalAdd('second', 1, $from);
1174 $from['M'] = $from['d'] = 1;
1175 $from['Y'] = $now['year'];
1177 $to['i'] = $to['s'] = 59;
1178 $to['d'] = $now['mday'];
1179 $to['M'] = $now['mon'];
1180 $to['Y'] = $now['year'];
1184 $to['d'] = $now['mday'];
1185 $to['M'] = $now['mon'];
1186 $to['Y'] = $now['year'];
1188 $to['i'] = $to['s'] = 59;
1189 $from = self
::intervalAdd('year', -2, $to);
1190 $from = self
::intervalAdd('second', 1, $from);
1194 $to['d'] = $now['mday'];
1195 $to['M'] = $now['mon'];
1196 $to['Y'] = $now['year'];
1198 $to['i'] = $to['s'] = 59;
1199 $from = self
::intervalAdd('year', -3, $to);
1200 $from = self
::intervalAdd('second', 1, $from);
1206 $to['Y'] = $now['year'];
1211 $from['M'] = $from['d'] = 1;
1214 $to['Y'] = $from['Y'] = $now['year'] +
1;
1218 $from['d'] = $now['mday'];
1219 $from['M'] = $now['mon'];
1220 $from['Y'] = $now['year'];
1221 $to['d'] = $now['mday'] - 1;
1222 $to['M'] = $now['mon'];
1223 $to['Y'] = $now['year'] +
1;
1227 switch ($relativeTermPrefix) {
1230 $to['d'] = $now['mday'];
1231 $to['M'] = $now['mon'];
1232 $to['Y'] = $now['year'];
1234 $to['i'] = $to['s'] = 59;
1235 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1236 $from = self
::intervalAdd('second', 1, $from);
1240 $from['d'] = $from['M'] = 1;
1243 $to['Y'] = $from['Y'] = $now['year'];
1244 if (is_numeric($relativeTermSuffix)) {
1245 $from['Y'] -= ($relativeTermSuffix - 1);
1254 $config = CRM_Core_Config
::singleton();
1255 $from['d'] = $config->fiscalYearStart
['d'];
1256 $from['M'] = $config->fiscalYearStart
['M'];
1257 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1258 switch ($relativeTermPrefix) {
1260 $from['Y'] = $fYear;
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'];
1267 $to['i'] = $to['s'] = 59;
1268 if (is_numeric($relativeTermSuffix)) {
1269 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1270 $from = self
::intervalAdd('second', 1, $from);
1275 if (!is_numeric($relativeTermSuffix)) {
1276 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1277 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1278 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1279 $to['d'] = $fiscalEnd['2'];
1280 $to['M'] = $fiscalEnd['1'];
1281 $to['Y'] = $fiscalEnd['0'];
1283 $to['i'] = $to['s'] = 59;
1286 $from['Y'] = $fYear - $relativeTermSuffix;
1287 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1288 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1289 $to['d'] = $fiscalEnd['2'];
1290 $to['M'] = $fiscalEnd['1'];
1293 $to['i'] = $to['s'] = 59;
1298 $from['Y'] = $fYear +
1;
1299 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1300 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1301 $to['d'] = $fiscalEnd['2'];
1302 $to['M'] = $fiscalEnd['1'];
1303 $to['Y'] = $fiscalEnd['0'];
1309 switch ($relativeTerm) {
1312 $quarter = ceil($now['mon'] / 3);
1314 $from['M'] = (3 * $quarter) - 2;
1315 $to['M'] = 3 * $quarter;
1316 $to['Y'] = $from['Y'] = $now['year'];
1317 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1322 $quarter = ceil($now['mon'] / 3);
1323 $quarter = $quarter - $difference;
1325 if ($quarter <= 0) {
1330 $from['M'] = (3 * $quarter) - 2;
1331 $to['M'] = 3 * $quarter;
1332 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1333 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1336 case 'previous_before':
1338 $quarter = ceil($now['mon'] / 3);
1339 $quarter = $quarter - $difference;
1341 if ($quarter <= 0) {
1346 $from['M'] = (3 * $quarter) - 2;
1347 $to['M'] = 3 * $quarter;
1348 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1349 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1354 $quarter = ceil($now['mon'] / 3);
1355 $current_quarter = $quarter;
1356 $quarter = $quarter - $difference;
1358 if ($quarter <= 0) {
1363 $from['M'] = (3 * $quarter) - 2;
1364 switch ($current_quarter) {
1366 $to['M'] = (4 * $quarter);
1370 $to['M'] = (4 * $quarter) +
3;
1374 $to['M'] = (4 * $quarter) +
2;
1378 $to['M'] = (4 * $quarter) +
1;
1381 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1382 if ($to['M'] > 12) {
1383 $to['M'] = 3 * ($quarter - 3);
1384 $to['Y'] = $now['year'];
1386 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1390 $quarter = ceil($now['mon'] / 3) - 1;
1392 if ($quarter <= 0) {
1396 $to['M'] = 3 * $quarter;
1397 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1398 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1403 $quarter = ceil($now['mon'] / 3);
1405 $from['M'] = (3 * $quarter) - 2;
1406 $from['Y'] = $now['year'];
1410 case 'greater_previous':
1411 $quarter = ceil($now['mon'] / 3) - 1;
1413 if ($quarter <= 0) {
1417 $from['M'] = 3 * $quarter;
1418 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1419 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1424 $to['d'] = $now['mday'];
1425 $to['M'] = $now['mon'];
1426 $to['Y'] = $now['year'];
1428 $to['i'] = $to['s'] = 59;
1429 $from = self
::intervalAdd('day', -90, $to);
1430 $from = self
::intervalAdd('second', 1, $from);
1434 $quarter = ceil($now['mon'] / 3);
1436 $from['M'] = (3 * $quarter) - 2;
1437 $from['Y'] = $now['year'];
1438 $to['d'] = $now['mday'];
1439 $to['M'] = $now['mon'];
1440 $to['Y'] = $now['year'];
1442 $to['i'] = $to['s'] = 59;
1446 $quarter = ceil($now['mon'] / 3);
1447 $to['M'] = 3 * $quarter;
1448 $to['Y'] = $now['year'];
1449 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1456 $quarter = ceil($now['mon'] / 3);
1457 $quarter = $quarter - $difference;
1460 $now['year'] = $now['year'] +
1;
1463 if ($quarter <= 0) {
1468 $from['M'] = (3 * $quarter) - 2;
1469 $to['M'] = 3 * $quarter;
1470 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1471 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1475 $from['d'] = $now['mday'];
1476 $from['M'] = $now['mon'];
1477 $from['Y'] = $now['year'];
1479 $from['i'] = $to['s'] = 00;
1480 $to = self
::intervalAdd('day', 90, $from);
1481 $to = self
::intervalAdd('second', -1, $to);
1485 if ($relativeTermPrefix === 'ending') {
1486 $to['d'] = $now['mday'];
1487 $to['M'] = $now['mon'];
1488 $to['Y'] = $now['year'];
1490 $to['i'] = $to['s'] = 59;
1491 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1492 $from = self
::intervalAdd('second', 1, $from);
1498 switch ($relativeTerm) {
1501 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1502 $from['M'] = $to['M'] = $now['mon'];
1503 $from['Y'] = $to['Y'] = $now['year'];
1508 if ($now['mon'] == 1) {
1509 $from['M'] = $to['M'] = 12;
1510 $from['Y'] = $to['Y'] = $now['year'] - 1;
1513 $from['M'] = $to['M'] = $now['mon'] - 1;
1514 $from['Y'] = $to['Y'] = $now['year'];
1516 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1519 case 'previous_before':
1521 if ($now['mon'] < 3) {
1522 $from['M'] = $to['M'] = 10 +
$now['mon'];
1523 $from['Y'] = $to['Y'] = $now['year'] - 1;
1526 $from['M'] = $to['M'] = $now['mon'] - 2;
1527 $from['Y'] = $to['Y'] = $now['year'];
1529 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1534 if ($now['mon'] < 3) {
1535 $from['M'] = 10 +
$now['mon'];
1536 $from['Y'] = $now['year'] - 1;
1539 $from['M'] = $now['mon'] - 2;
1540 $from['Y'] = $now['year'];
1543 if ($now['mon'] == 1) {
1545 $to['Y'] = $now['year'] - 1;
1548 $to['M'] = $now['mon'] - 1;
1549 $to['Y'] = $now['year'];
1552 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1556 // before end of past month
1557 if ($now['mon'] == 1) {
1559 $to['Y'] = $now['year'] - 1;
1562 $to['M'] = $now['mon'] - 1;
1563 $to['Y'] = $now['year'];
1566 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1572 $from['M'] = $now['mon'];
1573 $from['Y'] = $now['year'];
1577 case 'greater_previous':
1578 // from end of past month
1579 if ($now['mon'] == 1) {
1581 $from['Y'] = $now['year'] - 1;
1584 $from['M'] = $now['mon'] - 1;
1585 $from['Y'] = $now['year'];
1588 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1593 $to['d'] = $now['mday'];
1594 $to['M'] = $now['mon'];
1595 $to['Y'] = $now['year'];
1597 $to['i'] = $to['s'] = 59;
1598 $from = self
::intervalAdd('day', -60, $to);
1599 $from = self
::intervalAdd('second', 1, $from);
1603 $to['d'] = $now['mday'];
1604 $to['M'] = $now['mon'];
1605 $to['Y'] = $now['year'];
1607 $to['i'] = $to['s'] = 59;
1608 $from = self
::intervalAdd('day', -30, $to);
1609 $from = self
::intervalAdd('second', 1, $from);
1614 $from['M'] = $now['mon'];
1615 $from['Y'] = $now['year'];
1616 $to['d'] = $now['mday'];
1617 $to['M'] = $now['mon'];
1618 $to['Y'] = $now['year'];
1620 $to['i'] = $to['s'] = 59;
1625 $to['Y'] = $now['year'];
1626 $to['M'] = $now['mon'];
1627 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1633 if ($now['mon'] == 12) {
1634 $from['M'] = $to['M'] = 1;
1635 $from['Y'] = $to['Y'] = $now['year'] +
1;
1638 $from['M'] = $to['M'] = $now['mon'] +
1;
1639 $from['Y'] = $to['Y'] = $now['year'];
1641 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1645 $from['d'] = $now['mday'];
1646 $from['M'] = $now['mon'];
1647 $from['Y'] = $now['year'];
1649 $from['i'] = $to['s'] = 00;
1650 $to = self
::intervalAdd('day', 30, $from);
1651 $to = self
::intervalAdd('second', -1, $to);
1655 $from['d'] = $now['mday'];
1656 $from['M'] = $now['mon'];
1657 $from['Y'] = $now['year'];
1659 $from['i'] = $to['s'] = 00;
1660 $to = self
::intervalAdd('day', 60, $from);
1661 $to = self
::intervalAdd('second', -1, $to);
1665 if ($relativeTermPrefix === 'ending') {
1666 $to['d'] = $now['mday'];
1667 $to['M'] = $now['mon'];
1668 $to['Y'] = $now['year'];
1670 $to['i'] = $to['s'] = 59;
1671 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1672 $from = self
::intervalAdd('second', 1, $from);
1678 $weekFirst = Civi
::settings()->get('weekBegins');
1679 $thisDay = $now['wday'];
1680 if ($weekFirst > $thisDay) {
1681 $diffDay = $thisDay - $weekFirst +
7;
1684 $diffDay = $thisDay - $weekFirst;
1686 switch ($relativeTerm) {
1688 $from['d'] = $now['mday'];
1689 $from['M'] = $now['mon'];
1690 $from['Y'] = $now['year'];
1691 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1692 $to = self
::intervalAdd('day', 6, $from);
1696 $from['d'] = $now['mday'];
1697 $from['M'] = $now['mon'];
1698 $from['Y'] = $now['year'];
1699 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1700 $to = self
::intervalAdd('day', 6, $from);
1703 case 'previous_before':
1704 $from['d'] = $now['mday'];
1705 $from['M'] = $now['mon'];
1706 $from['Y'] = $now['year'];
1707 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1708 $to = self
::intervalAdd('day', 6, $from);
1712 $from['d'] = $now['mday'];
1713 $from['M'] = $now['mon'];
1714 $from['Y'] = $now['year'];
1715 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1716 $to = self
::intervalAdd('day', 13, $from);
1720 $to['d'] = $now['mday'];
1721 $to['M'] = $now['mon'];
1722 $to['Y'] = $now['year'];
1723 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1728 $from['d'] = $now['mday'];
1729 $from['M'] = $now['mon'];
1730 $from['Y'] = $now['year'];
1731 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1735 case 'greater_previous':
1736 $from['d'] = $now['mday'];
1737 $from['M'] = $now['mon'];
1738 $from['Y'] = $now['year'];
1739 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1744 $to['d'] = $now['mday'];
1745 $to['M'] = $now['mon'];
1746 $to['Y'] = $now['year'];
1748 $to['i'] = $to['s'] = 59;
1749 $from = self
::intervalAdd('day', -7, $to);
1750 $from = self
::intervalAdd('second', 1, $from);
1754 $from['d'] = $now['mday'];
1755 $from['M'] = $now['mon'];
1756 $from['Y'] = $now['year'];
1757 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1758 $to['d'] = $now['mday'];
1759 $to['M'] = $now['mon'];
1760 $to['Y'] = $now['year'];
1762 $to['i'] = $to['s'] = 59;
1766 $to['d'] = $now['mday'];
1767 $to['M'] = $now['mon'];
1768 $to['Y'] = $now['year'];
1770 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1775 $from['d'] = $now['mday'];
1776 $from['M'] = $now['mon'];
1777 $from['Y'] = $now['year'];
1778 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1779 $to = self
::intervalAdd('day', 6, $from);
1783 $from['d'] = $now['mday'];
1784 $from['M'] = $now['mon'];
1785 $from['Y'] = $now['year'];
1787 $from['i'] = $to['s'] = 00;
1788 $to = self
::intervalAdd('day', 7, $from);
1789 $to = self
::intervalAdd('second', -1, $to);
1793 if ($relativeTermPrefix === 'ending') {
1794 $to['d'] = $now['mday'];
1795 $to['M'] = $now['mon'];
1796 $to['Y'] = $now['year'];
1798 $to['i'] = $to['s'] = 59;
1799 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1800 $from = self
::intervalAdd('second', 1, $from);
1806 switch ($relativeTerm) {
1808 $from['d'] = $to['d'] = $now['mday'];
1809 $from['M'] = $to['M'] = $now['mon'];
1810 $from['Y'] = $to['Y'] = $now['year'];
1814 $from['d'] = $now['mday'];
1815 $from['M'] = $now['mon'];
1816 $from['Y'] = $now['year'];
1817 $from = self
::intervalAdd('day', -1, $from);
1818 $to['d'] = $from['d'];
1819 $to['M'] = $from['M'];
1820 $to['Y'] = $from['Y'];
1823 case 'previous_before':
1824 $from['d'] = $now['mday'];
1825 $from['M'] = $now['mon'];
1826 $from['Y'] = $now['year'];
1827 $from = self
::intervalAdd('day', -2, $from);
1828 $to['d'] = $from['d'];
1829 $to['M'] = $from['M'];
1830 $to['Y'] = $from['Y'];
1834 $from['d'] = $to['d'] = $now['mday'];
1835 $from['M'] = $to['M'] = $now['mon'];
1836 $from['Y'] = $to['Y'] = $now['year'];
1837 $from = self
::intervalAdd('day', -2, $from);
1838 $to = self
::intervalAdd('day', -1, $to);
1842 $to['d'] = $now['mday'];
1843 $to['M'] = $now['mon'];
1844 $to['Y'] = $now['year'];
1845 $to = self
::intervalAdd('day', -1, $to);
1850 $from['d'] = $now['mday'];
1851 $from['M'] = $now['mon'];
1852 $from['Y'] = $now['year'];
1857 $to['d'] = $now['mday'];
1858 $to['M'] = $now['mon'];
1859 $to['Y'] = $now['year'];
1860 $to = self
::intervalAdd('day', 1, $to);
1861 $from['d'] = $to['d'];
1862 $from['M'] = $to['M'];
1863 $from['Y'] = $to['Y'];
1867 if ($relativeTermPrefix === 'ending') {
1868 $to['d'] = $now['mday'];
1869 $to['M'] = $now['mon'];
1870 $to['Y'] = $now['year'];
1872 $to['i'] = $to['s'] = 59;
1873 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1874 $from = self
::intervalAdd('second', 1, $from);
1880 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1881 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1886 * Calculate current fiscal year based on the fiscal month and day.
1888 * @param int $fyDate
1889 * Fiscal start date.
1891 * @param int $fyMonth
1892 * Fiscal Start Month.
1895 * $fy Current Fiscal Year
1897 public static function calculateFiscalYear($fyDate, $fyMonth) {
1898 $date = date("Y-m-d");
1899 $currentYear = date("Y");
1901 // recalculate the date because month 4::04 make the difference
1902 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1903 $fyDate = $fiscalYear[2];
1904 $fyMonth = $fiscalYear[1];
1905 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1907 if ($fyStartDate > $date) {
1908 $fy = intval(intval($currentYear) - 1);
1911 $fy = intval($currentYear);
1917 * Function to process date, convert to mysql format
1919 * @param string $date
1921 * @param string $time
1923 * @param bool|string $returnNullString 'null' needs to be returned
1924 * so that db oject will set null in db
1925 * @param string $format
1926 * Expected return date format.( default is mysql ).
1929 * date format that is excepted by mysql
1931 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1934 if ($returnNullString) {
1935 $mysqlDate = 'null';
1939 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1946 * Add the metadata about a date field to the field.
1948 * This metadata will work with the call $form->add('datepicker', ...
1950 * @param array $fieldMetaData
1951 * @param array $field
1955 public static function addDateMetadataToField($fieldMetaData, $field) {
1956 if (isset($fieldMetaData['html'])) {
1957 $field['html_type'] = $fieldMetaData['html']['type'];
1958 if ($field['html_type'] === 'Select Date') {
1959 if (!isset($field['date_format'])) {
1960 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1961 $field['start_date_years'] = $dateAttributes['minYear'];
1962 $field['end_date_years'] = $dateAttributes['maxYear'];
1963 $field['date_format'] = $dateAttributes['format'];
1964 $field['is_datetime_field'] = TRUE;
1965 $field['time_format'] = $dateAttributes['time'];
1966 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1968 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1969 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1976 * Get the fields required for the 'extra' parameter when adding a datepicker.
1978 * @param array $field
1982 public static function getDatePickerExtra($field) {
1984 if (isset($field['date_format'])) {
1985 $extra['date'] = $field['date_format'];
1986 $extra['time'] = $field['time_format'];
1988 $thisYear = date('Y');
1989 if (isset($field['start_date_years'])) {
1990 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
1992 if (isset($field['end_date_years'])) {
1993 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
1999 * Get the attributes parameters required for datepicker.
2001 * @param array $field
2005 * Array ready to pass to $this->addForm('datepicker' as attributes.
2007 public static function getDatePickerAttributes(&$field) {
2010 'start_date_years' => 'minYear',
2011 'end_date_years' => 'maxYear',
2012 'date_format' => 'format',
2014 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2015 if (isset($field[$dateAttribute])) {
2016 $attributes[$mapTo] = $field[$dateAttribute];
2023 * Function to convert mysql to date plugin format.
2025 * @param string $mysqlDate
2028 * @param null $formatType
2029 * @param null $format
2030 * @param null $timeFormat
2035 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2036 // if date is not passed assume it as today
2038 $mysqlDate = date('Y-m-d G:i:s');
2041 $config = CRM_Core_Config
::singleton();
2043 // get actual format
2044 $params = ['name' => $formatType];
2046 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2048 if ($values['date_format']) {
2049 $format = $values['date_format'];
2052 if (isset($values['time_format'])) {
2053 $timeFormat = $values['time_format'];
2057 $dateFormat = 'm/d/Y';
2058 $date = date($dateFormat, strtotime($mysqlDate));
2061 $timeFormat = $config->timeInputFormat
;
2064 $actualTimeFormat = "g:iA";
2065 $appendZeroLength = 7;
2066 if ($timeFormat > 1) {
2067 $actualTimeFormat = "G:i";
2068 $appendZeroLength = 5;
2071 $time = date($actualTimeFormat, strtotime($mysqlDate));
2073 // need to append zero for hours < 10
2074 if (strlen($time) < $appendZeroLength) {
2075 $time = '0' . $time;
2078 return [$date, $time];
2082 * Function get date format.
2084 * @param string $formatType
2085 * Date name e.g. birth.
2089 public static function getDateFormat($formatType = NULL) {
2092 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2093 $formatType, 'date_format', 'name'
2098 $config = CRM_Core_Config
::singleton();
2099 $format = $config->dateInputFormat
;
2105 * Date formatting for imports where date format is specified.
2107 * Note this is used for imports (only) because the importer can
2108 * specify the format.
2110 * Tests are in CRM_Utils_DateTest::testFormatDate
2113 * Date string as entered.
2115 * One of the constants like CRM_Core_Form_Date::DATE_yyyy_mm_dd.
2117 * @return null|string
2119 public static function formatDate($date, $dateType) {
2124 // 1. first convert date to default format.
2125 // 2. append time to default formatted date (might be removed during format)
2126 // 3. validate date / date time.
2127 // 4. If date and time then convert to default date time format.
2130 $dateParams = [$dateKey => $date];
2132 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2133 $dateVal = $dateParams[$dateKey];
2134 if ($dateType == 1) {
2136 // The seconds part of this regex is not quite right - but it does succeed
2137 // in clarifying whether there is a time component or not - which is all it is meant
2139 if (preg_match('/(\s(([01]\d)|[2][0-3]):([0-5]\d):?[0-5]?\d?)$/', $date, $matches)) {
2140 if (strpos($date, '-') !== FALSE) {
2141 $dateVal .= array_shift($matches);
2143 if (!CRM_Utils_Rule
::dateTime($dateVal)) {
2146 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", '', $dateVal), '%Y%m%d%H%i%s');
2152 return CRM_Utils_Rule
::date($dateVal) ?
$dateVal : NULL;
2159 * Function to return days of the month.
2163 public static function getCalendarDayOfMonth() {
2165 for ($i = 1; $i <= 31; $i++
) {
2168 $month[$i] = $i . ' / Last day of month';
2175 * Convert a relative date format to an api field.
2177 * @param array $params
2178 * @param string $dateField
2179 * @param bool $isDatePicker
2180 * Non datepicker fields are deprecated. Exterminate Exterminate.
2181 * (but for now handle them).
2183 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2184 if (!empty($params[$dateField . '_relative'])) {
2185 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2186 unset($params[$dateField . '_relative']);
2188 if (!empty($params[$dateField . '_low'])) {
2189 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2190 unset($params[$dateField . '_low']);
2192 if (!empty($params[$dateField . '_high'])) {
2193 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2194 unset($params[$dateField . '_high']);
2196 if (empty($dates)) {
2199 if (empty($dates[0])) {
2200 $params[$dateField] = ['<=' => $dates[1]];
2202 elseif (empty($dates[1])) {
2203 $params[$dateField] = ['>=' => $dates[0]];
2206 $params[$dateField] = ['BETWEEN' => $dates];
2211 * Print out a date object in specified format in local timezone
2213 * @param DateTimeObject $dateObject
2214 * @param string $format
2217 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2218 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2219 $dateObject->setTimezone($systemTimeZone);
2220 return $dateObject->format($format);
2224 * Check if the value returned by a date picker has a date section (ie: includes
2225 * a '-' character) if it includes a time section (ie: includes a ':').
2227 * @param string $value
2228 * A date/time string input from a datepicker value.
2231 * TRUE if valid, FALSE if there is a time without a date.
2233 public static function datePickerValueWithTimeHasDate($value) {
2234 // If there's no : (time) or a : and a - (date) then return true
2236 strpos($value, ':') === FALSE
2237 ||
strpos($value, ':') !== FALSE && strpos($value, '-') !== FALSE
2242 * Validate start and end dates entered on a form to make sure they are
2243 * logical. Expects the form keys to be start_date and end_date.
2245 * @param string $startFormKey
2246 * The form element key of the 'start date'
2247 * @param string $startValue
2248 * The value of the 'start date'
2249 * @param string $endFormKey
2250 * The form element key of the 'end date'
2251 * @param string $endValue
2252 * The value of the 'end date'
2254 * @return array|bool
2255 * TRUE if valid, an array of the erroneous form key, and error message to
2258 public static function validateStartEndDatepickerInputs($startFormKey, $startValue, $endFormKey, $endValue) {
2260 // Check date as well as time is set
2261 if (!empty($startValue) && !self
::datePickerValueWithTimeHasDate($startValue)) {
2262 return ['key' => $startFormKey, 'message' => ts('Please enter a date as well as a time.')];
2264 if (!empty($endValue) && !self
::datePickerValueWithTimeHasDate($endValue)) {
2265 return ['key' => $endFormKey, 'message' => ts('Please enter a date as well as a time.')];
2268 // Check end date is after start date
2269 if (!empty($startValue) && !empty($endValue) && $endValue < $startValue) {
2270 return ['key' => $endFormKey, 'message' => ts('The end date should be after the start date.')];