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];
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);
374 $year = (int) substr($dateString, 0, 4);
375 $month = (int) substr($dateString, 4, 2);
376 $day = (int) substr($dateString, 6, 2);
378 $hour24 = (int) substr($dateString, 8, 2);
379 $minute = (int) substr($dateString, 10, 2);
382 if ($day %
10 == 1 and $day != 11) {
385 elseif ($day %
10 == 2 and $day != 12) {
388 elseif ($day %
10 == 3 and $day != 13) {
409 $hour12 = $hour24 - 12;
415 '%b' => $abbrMonths[$month] ??
NULL,
416 '%B' => $fullMonths[$month] ??
NULL,
417 '%d' => $day > 9 ?
$day : '0' . $day,
418 '%e' => $day > 9 ?
$day : ' ' . $day,
421 '%H' => $hour24 > 9 ?
$hour24 : '0' . $hour24,
422 '%h' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
423 '%I' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
424 '%k' => $hour24 > 9 ?
$hour24 : ' ' . $hour24,
425 '%l' => $hour12 > 9 ?
$hour12 : ' ' . $hour12,
426 '%m' => $month > 9 ?
$month : '0' . $month,
427 '%M' => $minute > 9 ?
$minute : '0' . $minute,
428 '%i' => $minute > 9 ?
$minute : '0' . $minute,
429 '%p' => strtolower($type),
435 return strtr($format, $date);
443 * Format the field according to the site's preferred date format.
445 * This is likely to look something like December 31st, 2020.
447 * @param string $date
451 public static function formatDateOnlyLong(string $date):string {
452 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
456 * Wrapper for customFormat that takes a timestamp
458 * @param int $timestamp
459 * Date and time in timestamp format.
460 * @param string $format
462 * @param array $dateParts
463 * An array with the desired date parts.
466 * the $format-formatted $date
468 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
469 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
473 * Converts the date/datetime from MySQL format to ISO format
475 * @param string $mysql
476 * Date/datetime in MySQL format.
479 * date/datetime in ISO format
481 public static function mysqlToIso($mysql) {
482 $year = substr($mysql, 0, 4);
483 $month = substr($mysql, 4, 2);
484 $day = substr($mysql, 6, 2);
485 $hour = substr($mysql, 8, 2);
486 $minute = substr($mysql, 10, 2);
487 $second = substr($mysql, 12, 2);
513 * Converts the date/datetime from ISO format to MySQL format
514 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
515 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
516 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
519 * Date/datetime in ISO format.
522 * date/datetime in MySQL format
524 public static function isoToMysql($iso) {
525 $dropArray = ['-' => '', ':' => '', ' ' => ''];
526 return strtr($iso, $dropArray);
530 * Converts the any given date to default date format.
532 * @param array $params
533 * Has given date-format.
534 * @param int $dateType
536 * @param string $dateParam
541 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
543 $cen = substr($now['year'], 0, 2);
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;
696 $year = (int ) $year;
697 // simple heuristic to determine what century to use
698 // 00 - 20 is always 2000 - 2020
699 // 21 - 99 is always 1921 - 1999
701 $year = (strlen($year) == 1) ?
$cen . '0' . $year : $cen . $year;
703 elseif ($year < 100) {
704 $year = $prevCen . $year;
707 if ($params[$dateParam]) {
708 $params[$dateParam] = "$year$month$day";
710 // if month is invalid return as error
711 if ($month !== '00' && $month <= 12) {
722 public static function isDate(&$date) {
723 if (CRM_Utils_System
::isNull($date)) {
730 * Translate a TTL to a concrete expiration time.
732 * @param NULL|int|DateInterval $ttl
733 * @param int $default
734 * The value to use if $ttl is not specified (NULL).
736 * Timestamp (seconds since epoch).
737 * @throws \CRM_Utils_Cache_InvalidArgumentException
739 public static function convertCacheTtlToExpires($ttl, $default) {
745 return time() +
$ttl;
747 elseif ($ttl instanceof DateInterval
) {
748 return date_add(new DateTime(), $ttl)->getTimestamp();
751 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
758 * @param NULL|int|DateInterval $ttl
759 * @param int $default
760 * The value to use if $ttl is not specified (NULL).
762 * Seconds until expiration.
763 * @throws \CRM_Utils_Cache_InvalidArgumentException
765 public static function convertCacheTtl($ttl, $default) {
769 elseif (is_int($ttl)) {
772 elseif ($ttl instanceof DateInterval
) {
773 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
776 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
781 * @param null $timeStamp
783 * @return bool|string
785 public static function currentDBDate($timeStamp = NULL) {
786 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
795 public static function overdue($date, $now = NULL) {
796 $mysqlDate = self
::isoToMysql($date);
798 $now = self
::currentDBDate();
801 $now = self
::isoToMysql($now);
804 return !(strtotime($mysqlDate) >= strtotime($now));
808 * Get customized today.
810 * This function is used for getting customized today. To get
811 * actuall today pass 'dayParams' as null. or else pass the day,
812 * month, year values as array values
813 * Example: $dayParams = array(
814 * 'day' => '25', 'month' => '10',
815 * 'year' => '2007' );
817 * @param array $dayParams of the day, month, year.
818 * Array of the day, month, year.
820 * @param string $format
821 * Expected date format( default.
822 * format is 2007-12-21 )
825 * Return the customized today's date (Y-m-d)
827 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
828 if (is_null($dayParams) ||
empty($dayParams)) {
829 $today = date($format);
832 $today = date($format, mktime(0, 0, 0,
843 * Find whether today's date lies in
846 * @param date $startDate
847 * Start date for the range.
848 * @param date $endDate
849 * End date for the range.
852 * true if today's date is in the given date range
854 public static function getRange($startDate, $endDate) {
855 $today = date("Y-m-d");
856 $mysqlStartDate = self
::isoToMysql($startDate);
857 $mysqlEndDate = self
::isoToMysql($endDate);
858 $mysqlToday = self
::isoToMysql($today);
860 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
863 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
866 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
873 * Get start date and end from
874 * the given relative term and unit
876 * @param string $relative Relative format in the format term.unit.
879 * @param string $from
881 * @param string $fromTime
882 * @param string $toTime
885 * start date, end date
887 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
889 list($term, $unit) = explode('.', $relative, 2);
890 $dateRange = self
::relativeToAbsolute($term, $unit);
891 $from = substr($dateRange['from'], 0, 8);
892 $to = substr($dateRange['to'], 0, 8);
893 // @todo fix relativeToAbsolute & add tests
894 // relativeToAbsolute returns 8 char date strings
895 // or 14 char date + time strings.
896 // We should use those. However, it turns out to be unreliable.
897 // e.g. this.week does NOT return 235959 for 'from'
898 // so our defaults are more reliable.
899 // Currently relativeToAbsolute only supports 'whole' days so that is ok
902 $from = self
::processDate($from, $fromTime);
903 $to = self
::processDate($to, $toTime);
909 * Calculate Age in Years if greater than one year else in months.
911 * @param date $birthDate
913 * @param date $targetDate
914 * Target Date. (show age on specific date)
917 * array $results contains years or months
919 public static function calculateAge($birthDate, $targetDate = NULL) {
921 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
923 $bDate = explode('-', $formatedBirthDate);
924 $birthYear = $bDate[0];
925 $birthMonth = $bDate[1];
926 $birthDay = $bDate[2];
927 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
929 $year_diff = date("Y", $targetDate) - $birthYear;
931 // don't calculate age CRM-3143
932 if ($birthYear == '1902') {
935 switch ($year_diff) {
937 $month = (12 - $birthMonth) +
date("m", $targetDate);
939 if (date("d", $targetDate) < $birthDay) {
942 $results['months'] = $month;
944 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
945 $results['months'] = $month - 1;
948 $results['years'] = $year_diff;
953 $month = date("m", $targetDate) - $birthMonth;
954 $results['months'] = $month;
958 $results['years'] = $year_diff;
959 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
968 * Calculate next payment date according to provided unit & interval
970 * @param string $unit
971 * Frequency unit like year,month, week etc.
973 * @param int $interval
974 * Frequency interval.
977 * Start date of pledge.
979 * @param bool $dontCareTime
982 * contains new date with added interval
984 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
985 if (is_array($date)) {
986 $hour = $date['H'] ??
'00';
987 $minute = $date['i'] ??
'00';
988 $second = $date['s'] ??
'00';
989 $month = $date['M'] ??
NULL;
990 $day = $date['d'] ??
NULL;
991 $year = $date['Y'] ??
NULL;
994 extract(date_parse($date));
996 $date = mktime($hour, $minute, $second, $month, $day, $year);
999 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
1003 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
1007 $interval = $interval * 7;
1008 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1012 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1016 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1020 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1023 $date['M'] = $scheduleDate[0];
1024 $date['d'] = $scheduleDate[1];
1025 $date['Y'] = $scheduleDate[2];
1026 if ($dontCareTime == FALSE) {
1027 $date['H'] = $scheduleDate[3];
1028 $date['i'] = $scheduleDate[4];
1029 $date['s'] = $scheduleDate[5];
1035 * Get the smarty view presentation mapping for the given format.
1037 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1038 * they should be rendered using a longer date format. This is likely as much to
1039 * do with the earlier date widget being unable to handle some formats as usablity.
1040 * However, we continue to respect this.
1043 * Given format ( eg 'M Y', 'Y M' ).
1045 * @return string|null
1046 * Smarty translation of the date format. Null is also valid and is translated
1047 * according to the available parts at the smarty layer.
1049 public static function getDateFieldViewFormat($format) {
1050 $supportableFormats = [
1051 'mm/dd' => '%B %E%f',
1052 'dd-mm' => '%E%f %B',
1056 'dd/mm/yy' => '%E%f %B %Y',
1059 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1063 * Pick the smarty format from settings that best matches the time string we have.
1065 * For view purposes we historically use the setting that most closely matches the data
1066 * in the format from our settings, as opposed to the setting configured for the field.
1071 public static function pickBestSmartyFormat($format) {
1072 if (stristr($format, 'h')) {
1073 return Civi
::settings()->get('dateformatDatetime');
1075 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1076 return Civi
::settings()->get('dateformatFull');
1078 if (stristr($format, 'm')) {
1079 return Civi
::settings()->get('dateformatPartial');
1081 return Civi
::settings()->get('dateformatYear');
1085 * Map date plugin and actual format that is used by PHP.
1089 public static function datePluginToPHPFormats() {
1090 $dateInputFormats = [
1091 "mm/dd/yy" => 'm/d/Y',
1092 "dd/mm/yy" => 'd/m/Y',
1093 "yy-mm-dd" => 'Y-m-d',
1094 "dd-mm-yy" => 'd-m-Y',
1095 "dd.mm.yy" => 'd.m.Y',
1097 "M d, yy" => 'M j, Y',
1098 "d M yy" => 'j M Y',
1099 "MM d, yy" => 'F j, Y',
1100 "d MM yy" => 'j F Y',
1101 "DD, d MM yy" => 'l, j F Y',
1109 return $dateInputFormats;
1113 * Resolves the given relative time interval into finite time limits.
1115 * @param string $relativeTerm
1116 * Relative time frame: this, previous, previous_1.
1118 * Frequency unit like year, month, week etc.
1121 * start date and end date for the relative time frame
1123 public static function relativeToAbsolute($relativeTerm, $unit) {
1125 $from = $to = $dateRange = [];
1126 $from['H'] = $from['i'] = $from['s'] = 0;
1127 $relativeTermParts = explode('_', $relativeTerm);
1128 $relativeTermPrefix = $relativeTermParts[0];
1129 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1133 switch ($relativeTerm) {
1135 $from['M'] = $from['d'] = 1;
1138 $to['Y'] = $from['Y'] = $now['year'] - 1;
1141 case 'previous_before':
1142 $from['M'] = $from['d'] = 1;
1145 $to['Y'] = $from['Y'] = $now['year'] - 2;
1149 $from['M'] = $from['d'] = 1;
1152 $from['Y'] = $now['year'] - 2;
1153 $to['Y'] = $now['year'] - 1;
1159 $to['Y'] = $now['year'] - 1;
1164 $from['M'] = $from['d'] = 1;
1165 $from['Y'] = $now['year'];
1169 case 'greater_previous':
1172 $from['Y'] = $now['year'] - 1;
1177 $to['d'] = $now['mday'];
1178 $to['M'] = $now['mon'];
1179 $to['Y'] = $now['year'];
1181 $to['i'] = $to['s'] = 59;
1182 $from = self
::intervalAdd('year', -1, $to);
1183 $from = self
::intervalAdd('second', 1, $from);
1187 $from['M'] = $from['d'] = 1;
1188 $from['Y'] = $now['year'];
1190 $to['i'] = $to['s'] = 59;
1191 $to['d'] = $now['mday'];
1192 $to['M'] = $now['mon'];
1193 $to['Y'] = $now['year'];
1197 $to['d'] = $now['mday'];
1198 $to['M'] = $now['mon'];
1199 $to['Y'] = $now['year'];
1201 $to['i'] = $to['s'] = 59;
1202 $from = self
::intervalAdd('year', -2, $to);
1203 $from = self
::intervalAdd('second', 1, $from);
1207 $to['d'] = $now['mday'];
1208 $to['M'] = $now['mon'];
1209 $to['Y'] = $now['year'];
1211 $to['i'] = $to['s'] = 59;
1212 $from = self
::intervalAdd('year', -3, $to);
1213 $from = self
::intervalAdd('second', 1, $from);
1219 $to['Y'] = $now['year'];
1224 $from['M'] = $from['d'] = 1;
1227 $to['Y'] = $from['Y'] = $now['year'] +
1;
1231 $from['d'] = $now['mday'];
1232 $from['M'] = $now['mon'];
1233 $from['Y'] = $now['year'];
1234 $to['d'] = $now['mday'] - 1;
1235 $to['M'] = $now['mon'];
1236 $to['Y'] = $now['year'] +
1;
1240 switch ($relativeTermPrefix) {
1243 $to['d'] = $now['mday'];
1244 $to['M'] = $now['mon'];
1245 $to['Y'] = $now['year'];
1247 $to['i'] = $to['s'] = 59;
1248 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1249 $from = self
::intervalAdd('second', 1, $from);
1253 $from['d'] = $from['M'] = 1;
1256 $to['Y'] = $from['Y'] = $now['year'];
1257 if (is_numeric($relativeTermSuffix)) {
1258 $from['Y'] -= ($relativeTermSuffix - 1);
1267 $config = CRM_Core_Config
::singleton();
1268 $from['d'] = $config->fiscalYearStart
['d'];
1269 $from['M'] = $config->fiscalYearStart
['M'];
1270 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1271 switch ($relativeTermPrefix) {
1273 $from['Y'] = $fYear;
1274 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1275 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1276 $to['d'] = $fiscalEnd['2'];
1277 $to['M'] = $fiscalEnd['1'];
1278 $to['Y'] = $fiscalEnd['0'];
1280 $to['i'] = $to['s'] = 59;
1281 if (is_numeric($relativeTermSuffix)) {
1282 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1283 $from = self
::intervalAdd('second', 1, $from);
1288 if (!is_numeric($relativeTermSuffix)) {
1289 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1290 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1291 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1292 $to['d'] = $fiscalEnd['2'];
1293 $to['M'] = $fiscalEnd['1'];
1294 $to['Y'] = $fiscalEnd['0'];
1296 $to['i'] = $to['s'] = 59;
1299 $from['Y'] = $fYear - $relativeTermSuffix;
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'];
1306 $to['i'] = $to['s'] = 59;
1311 $from['Y'] = $fYear +
1;
1312 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1313 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1314 $to['d'] = $fiscalEnd['2'];
1315 $to['M'] = $fiscalEnd['1'];
1316 $to['Y'] = $fiscalEnd['0'];
1322 switch ($relativeTerm) {
1325 $quarter = ceil($now['mon'] / 3);
1327 $from['M'] = (3 * $quarter) - 2;
1328 $to['M'] = 3 * $quarter;
1329 $to['Y'] = $from['Y'] = $now['year'];
1330 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1335 $quarter = ceil($now['mon'] / 3);
1336 $quarter = $quarter - $difference;
1338 if ($quarter <= 0) {
1343 $from['M'] = (3 * $quarter) - 2;
1344 $to['M'] = 3 * $quarter;
1345 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1346 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1349 case 'previous_before':
1351 $quarter = ceil($now['mon'] / 3);
1352 $quarter = $quarter - $difference;
1354 if ($quarter <= 0) {
1359 $from['M'] = (3 * $quarter) - 2;
1360 $to['M'] = 3 * $quarter;
1361 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1362 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1367 $quarter = ceil($now['mon'] / 3);
1368 $current_quarter = $quarter;
1369 $quarter = $quarter - $difference;
1371 if ($quarter <= 0) {
1376 $from['M'] = (3 * $quarter) - 2;
1377 switch ($current_quarter) {
1379 $to['M'] = (4 * $quarter);
1383 $to['M'] = (4 * $quarter) +
3;
1387 $to['M'] = (4 * $quarter) +
2;
1391 $to['M'] = (4 * $quarter) +
1;
1394 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1395 if ($to['M'] > 12) {
1396 $to['M'] = 3 * ($quarter - 3);
1397 $to['Y'] = $now['year'];
1399 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1403 $quarter = ceil($now['mon'] / 3) - 1;
1405 if ($quarter <= 0) {
1409 $to['M'] = 3 * $quarter;
1410 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1411 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1416 $quarter = ceil($now['mon'] / 3);
1418 $from['M'] = (3 * $quarter) - 2;
1419 $from['Y'] = $now['year'];
1423 case 'greater_previous':
1424 $quarter = ceil($now['mon'] / 3) - 1;
1426 if ($quarter <= 0) {
1430 $from['M'] = 3 * $quarter;
1431 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1432 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1437 $to['d'] = $now['mday'];
1438 $to['M'] = $now['mon'];
1439 $to['Y'] = $now['year'];
1441 $to['i'] = $to['s'] = 59;
1442 $from = self
::intervalAdd('day', -90, $to);
1443 $from = self
::intervalAdd('second', 1, $from);
1447 $quarter = ceil($now['mon'] / 3);
1449 $from['M'] = (3 * $quarter) - 2;
1450 $from['Y'] = $now['year'];
1451 $to['d'] = $now['mday'];
1452 $to['M'] = $now['mon'];
1453 $to['Y'] = $now['year'];
1455 $to['i'] = $to['s'] = 59;
1459 $quarter = ceil($now['mon'] / 3);
1460 $to['M'] = 3 * $quarter;
1461 $to['Y'] = $now['year'];
1462 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1469 $quarter = ceil($now['mon'] / 3);
1470 $quarter = $quarter - $difference;
1473 $now['year'] = $now['year'] +
1;
1476 if ($quarter <= 0) {
1481 $from['M'] = (3 * $quarter) - 2;
1482 $to['M'] = 3 * $quarter;
1483 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1484 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1488 $from['d'] = $now['mday'];
1489 $from['M'] = $now['mon'];
1490 $from['Y'] = $now['year'];
1492 $from['i'] = $to['s'] = 00;
1493 $to = self
::intervalAdd('day', 90, $from);
1494 $to = self
::intervalAdd('second', -1, $to);
1498 if ($relativeTermPrefix === 'ending') {
1499 $to['d'] = $now['mday'];
1500 $to['M'] = $now['mon'];
1501 $to['Y'] = $now['year'];
1503 $to['i'] = $to['s'] = 59;
1504 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1505 $from = self
::intervalAdd('second', 1, $from);
1511 switch ($relativeTerm) {
1514 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1515 $from['M'] = $to['M'] = $now['mon'];
1516 $from['Y'] = $to['Y'] = $now['year'];
1521 if ($now['mon'] == 1) {
1522 $from['M'] = $to['M'] = 12;
1523 $from['Y'] = $to['Y'] = $now['year'] - 1;
1526 $from['M'] = $to['M'] = $now['mon'] - 1;
1527 $from['Y'] = $to['Y'] = $now['year'];
1529 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1532 case 'previous_before':
1534 if ($now['mon'] < 3) {
1535 $from['M'] = $to['M'] = 10 +
$now['mon'];
1536 $from['Y'] = $to['Y'] = $now['year'] - 1;
1539 $from['M'] = $to['M'] = $now['mon'] - 2;
1540 $from['Y'] = $to['Y'] = $now['year'];
1542 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1547 if ($now['mon'] < 3) {
1548 $from['M'] = 10 +
$now['mon'];
1549 $from['Y'] = $now['year'] - 1;
1552 $from['M'] = $now['mon'] - 2;
1553 $from['Y'] = $now['year'];
1556 if ($now['mon'] == 1) {
1558 $to['Y'] = $now['year'] - 1;
1561 $to['M'] = $now['mon'] - 1;
1562 $to['Y'] = $now['year'];
1565 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1569 // before end of past month
1570 if ($now['mon'] == 1) {
1572 $to['Y'] = $now['year'] - 1;
1575 $to['M'] = $now['mon'] - 1;
1576 $to['Y'] = $now['year'];
1579 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1585 $from['M'] = $now['mon'];
1586 $from['Y'] = $now['year'];
1590 case 'greater_previous':
1591 // from end of past month
1592 if ($now['mon'] == 1) {
1594 $from['Y'] = $now['year'] - 1;
1597 $from['M'] = $now['mon'] - 1;
1598 $from['Y'] = $now['year'];
1601 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1606 $to['d'] = $now['mday'];
1607 $to['M'] = $now['mon'];
1608 $to['Y'] = $now['year'];
1610 $to['i'] = $to['s'] = 59;
1611 $from = self
::intervalAdd('day', -60, $to);
1612 $from = self
::intervalAdd('second', 1, $from);
1616 $to['d'] = $now['mday'];
1617 $to['M'] = $now['mon'];
1618 $to['Y'] = $now['year'];
1620 $to['i'] = $to['s'] = 59;
1621 $from = self
::intervalAdd('day', -30, $to);
1622 $from = self
::intervalAdd('second', 1, $from);
1627 $from['M'] = $now['mon'];
1628 $from['Y'] = $now['year'];
1629 $to['d'] = $now['mday'];
1630 $to['M'] = $now['mon'];
1631 $to['Y'] = $now['year'];
1633 $to['i'] = $to['s'] = 59;
1638 $to['Y'] = $now['year'];
1639 $to['M'] = $now['mon'];
1640 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1646 if ($now['mon'] == 12) {
1647 $from['M'] = $to['M'] = 1;
1648 $from['Y'] = $to['Y'] = $now['year'] +
1;
1651 $from['M'] = $to['M'] = $now['mon'] +
1;
1652 $from['Y'] = $to['Y'] = $now['year'];
1654 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1658 $from['d'] = $now['mday'];
1659 $from['M'] = $now['mon'];
1660 $from['Y'] = $now['year'];
1662 $from['i'] = $to['s'] = 00;
1663 $to = self
::intervalAdd('day', 30, $from);
1664 $to = self
::intervalAdd('second', -1, $to);
1668 $from['d'] = $now['mday'];
1669 $from['M'] = $now['mon'];
1670 $from['Y'] = $now['year'];
1672 $from['i'] = $to['s'] = 00;
1673 $to = self
::intervalAdd('day', 60, $from);
1674 $to = self
::intervalAdd('second', -1, $to);
1678 if ($relativeTermPrefix === 'ending') {
1679 $to['d'] = $now['mday'];
1680 $to['M'] = $now['mon'];
1681 $to['Y'] = $now['year'];
1683 $to['i'] = $to['s'] = 59;
1684 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1685 $from = self
::intervalAdd('second', 1, $from);
1691 $weekFirst = Civi
::settings()->get('weekBegins');
1692 $thisDay = $now['wday'];
1693 if ($weekFirst > $thisDay) {
1694 $diffDay = $thisDay - $weekFirst +
7;
1697 $diffDay = $thisDay - $weekFirst;
1699 switch ($relativeTerm) {
1701 $from['d'] = $now['mday'];
1702 $from['M'] = $now['mon'];
1703 $from['Y'] = $now['year'];
1704 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1705 $to = self
::intervalAdd('day', 6, $from);
1709 $from['d'] = $now['mday'];
1710 $from['M'] = $now['mon'];
1711 $from['Y'] = $now['year'];
1712 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1713 $to = self
::intervalAdd('day', 6, $from);
1716 case 'previous_before':
1717 $from['d'] = $now['mday'];
1718 $from['M'] = $now['mon'];
1719 $from['Y'] = $now['year'];
1720 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1721 $to = self
::intervalAdd('day', 6, $from);
1725 $from['d'] = $now['mday'];
1726 $from['M'] = $now['mon'];
1727 $from['Y'] = $now['year'];
1728 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1729 $to = self
::intervalAdd('day', 13, $from);
1733 $to['d'] = $now['mday'];
1734 $to['M'] = $now['mon'];
1735 $to['Y'] = $now['year'];
1736 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1741 $from['d'] = $now['mday'];
1742 $from['M'] = $now['mon'];
1743 $from['Y'] = $now['year'];
1744 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1748 case 'greater_previous':
1749 $from['d'] = $now['mday'];
1750 $from['M'] = $now['mon'];
1751 $from['Y'] = $now['year'];
1752 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1757 $to['d'] = $now['mday'];
1758 $to['M'] = $now['mon'];
1759 $to['Y'] = $now['year'];
1761 $to['i'] = $to['s'] = 59;
1762 $from = self
::intervalAdd('day', -7, $to);
1763 $from = self
::intervalAdd('second', 1, $from);
1767 $from['d'] = $now['mday'];
1768 $from['M'] = $now['mon'];
1769 $from['Y'] = $now['year'];
1770 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1771 $to['d'] = $now['mday'];
1772 $to['M'] = $now['mon'];
1773 $to['Y'] = $now['year'];
1775 $to['i'] = $to['s'] = 59;
1779 $to['d'] = $now['mday'];
1780 $to['M'] = $now['mon'];
1781 $to['Y'] = $now['year'];
1783 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1788 $from['d'] = $now['mday'];
1789 $from['M'] = $now['mon'];
1790 $from['Y'] = $now['year'];
1791 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1792 $to = self
::intervalAdd('day', 6, $from);
1796 $from['d'] = $now['mday'];
1797 $from['M'] = $now['mon'];
1798 $from['Y'] = $now['year'];
1800 $from['i'] = $to['s'] = 00;
1801 $to = self
::intervalAdd('day', 7, $from);
1802 $to = self
::intervalAdd('second', -1, $to);
1806 if ($relativeTermPrefix === 'ending') {
1807 $to['d'] = $now['mday'];
1808 $to['M'] = $now['mon'];
1809 $to['Y'] = $now['year'];
1811 $to['i'] = $to['s'] = 59;
1812 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1813 $from = self
::intervalAdd('second', 1, $from);
1819 switch ($relativeTerm) {
1821 $from['d'] = $to['d'] = $now['mday'];
1822 $from['M'] = $to['M'] = $now['mon'];
1823 $from['Y'] = $to['Y'] = $now['year'];
1827 $from['d'] = $now['mday'];
1828 $from['M'] = $now['mon'];
1829 $from['Y'] = $now['year'];
1830 $from = self
::intervalAdd('day', -1, $from);
1831 $to['d'] = $from['d'];
1832 $to['M'] = $from['M'];
1833 $to['Y'] = $from['Y'];
1836 case 'previous_before':
1837 $from['d'] = $now['mday'];
1838 $from['M'] = $now['mon'];
1839 $from['Y'] = $now['year'];
1840 $from = self
::intervalAdd('day', -2, $from);
1841 $to['d'] = $from['d'];
1842 $to['M'] = $from['M'];
1843 $to['Y'] = $from['Y'];
1847 $from['d'] = $to['d'] = $now['mday'];
1848 $from['M'] = $to['M'] = $now['mon'];
1849 $from['Y'] = $to['Y'] = $now['year'];
1850 $from = self
::intervalAdd('day', -2, $from);
1851 $to = self
::intervalAdd('day', -1, $to);
1855 $to['d'] = $now['mday'];
1856 $to['M'] = $now['mon'];
1857 $to['Y'] = $now['year'];
1858 $to = self
::intervalAdd('day', -1, $to);
1863 $from['d'] = $now['mday'];
1864 $from['M'] = $now['mon'];
1865 $from['Y'] = $now['year'];
1870 $to['d'] = $now['mday'];
1871 $to['M'] = $now['mon'];
1872 $to['Y'] = $now['year'];
1873 $to = self
::intervalAdd('day', 1, $to);
1874 $from['d'] = $to['d'];
1875 $from['M'] = $to['M'];
1876 $from['Y'] = $to['Y'];
1880 if ($relativeTermPrefix === 'ending') {
1881 $to['d'] = $now['mday'];
1882 $to['M'] = $now['mon'];
1883 $to['Y'] = $now['year'];
1885 $to['i'] = $to['s'] = 59;
1886 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1887 $from = self
::intervalAdd('second', 1, $from);
1893 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1894 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1899 * Calculate current fiscal year based on the fiscal month and day.
1901 * @param int $fyDate
1902 * Fiscal start date.
1904 * @param int $fyMonth
1905 * Fiscal Start Month.
1908 * $fy Current Fiscal Year
1910 public static function calculateFiscalYear($fyDate, $fyMonth) {
1911 $date = date("Y-m-d");
1912 $currentYear = date("Y");
1914 // recalculate the date because month 4::04 make the difference
1915 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1916 $fyDate = $fiscalYear[2];
1917 $fyMonth = $fiscalYear[1];
1918 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1920 if ($fyStartDate > $date) {
1921 $fy = intval(intval($currentYear) - 1);
1924 $fy = intval($currentYear);
1930 * Function to process date, convert to mysql format
1932 * @param string $date
1934 * @param string $time
1936 * @param bool|string $returnNullString 'null' needs to be returned
1937 * so that db oject will set null in db
1938 * @param string $format
1939 * Expected return date format.( default is mysql ).
1942 * date format that is excepted by mysql
1944 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1947 if ($returnNullString) {
1948 $mysqlDate = 'null';
1952 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1959 * Add the metadata about a date field to the field.
1961 * This metadata will work with the call $form->add('datepicker', ...
1963 * @param array $fieldMetaData
1964 * @param array $field
1968 public static function addDateMetadataToField($fieldMetaData, $field) {
1969 if (isset($fieldMetaData['html'])) {
1970 $field['html_type'] = $fieldMetaData['html']['type'];
1971 if ($field['html_type'] === 'Select Date') {
1972 if (!isset($field['date_format'])) {
1973 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1974 $field['start_date_years'] = $dateAttributes['minYear'];
1975 $field['end_date_years'] = $dateAttributes['maxYear'];
1976 $field['date_format'] = $dateAttributes['format'];
1977 $field['is_datetime_field'] = TRUE;
1978 $field['time_format'] = $dateAttributes['time'];
1979 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1981 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1982 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
1989 * Get the fields required for the 'extra' parameter when adding a datepicker.
1991 * @param array $field
1995 public static function getDatePickerExtra($field) {
1997 if (isset($field['date_format'])) {
1998 $extra['date'] = $field['date_format'];
1999 $extra['time'] = $field['time_format'];
2001 $thisYear = date('Y');
2002 if (isset($field['start_date_years'])) {
2003 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
2005 if (isset($field['end_date_years'])) {
2006 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
2012 * Get the attributes parameters required for datepicker.
2014 * @param array $field
2018 * Array ready to pass to $this->addForm('datepicker' as attributes.
2020 public static function getDatePickerAttributes(&$field) {
2023 'start_date_years' => 'minYear',
2024 'end_date_years' => 'maxYear',
2025 'date_format' => 'format',
2027 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2028 if (isset($field[$dateAttribute])) {
2029 $attributes[$mapTo] = $field[$dateAttribute];
2036 * Function to convert mysql to date plugin format.
2038 * @param string $mysqlDate
2041 * @param null $formatType
2042 * @param null $format
2043 * @param null $timeFormat
2048 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2049 // if date is not passed assume it as today
2051 $mysqlDate = date('Y-m-d G:i:s');
2054 $config = CRM_Core_Config
::singleton();
2056 // get actual format
2057 $params = ['name' => $formatType];
2059 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2061 if ($values['date_format']) {
2062 $format = $values['date_format'];
2065 if (isset($values['time_format'])) {
2066 $timeFormat = $values['time_format'];
2070 $dateFormat = 'm/d/Y';
2071 $date = date($dateFormat, strtotime($mysqlDate));
2074 $timeFormat = $config->timeInputFormat
;
2077 $actualTimeFormat = "g:iA";
2078 $appendZeroLength = 7;
2079 if ($timeFormat > 1) {
2080 $actualTimeFormat = "G:i";
2081 $appendZeroLength = 5;
2084 $time = date($actualTimeFormat, strtotime($mysqlDate));
2086 // need to append zero for hours < 10
2087 if (strlen($time) < $appendZeroLength) {
2088 $time = '0' . $time;
2091 return [$date, $time];
2095 * Function get date format.
2097 * @param string $formatType
2098 * Date name e.g. birth.
2102 public static function getDateFormat($formatType = NULL) {
2105 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2106 $formatType, 'date_format', 'name'
2111 $config = CRM_Core_Config
::singleton();
2112 $format = $config->dateInputFormat
;
2121 * @return null|string
2123 public static function formatDate($date, $dateType) {
2124 $formattedDate = NULL;
2126 return $formattedDate;
2129 // 1. first convert date to default format.
2130 // 2. append time to default formatted date (might be removed during format)
2131 // 3. validate date / date time.
2132 // 4. If date and time then convert to default date time format.
2135 $dateParams = [$dateKey => $date];
2137 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2138 $dateVal = $dateParams[$dateKey];
2140 if ($dateType == 1) {
2142 if (preg_match("/(\s(([01]\d)|[2][0-3]):([0-5]\d))$/", $date, $matches)) {
2143 $ruleName = 'dateTime';
2144 if (strpos($date, '-') !== FALSE) {
2145 $dateVal .= array_shift($matches);
2151 $valid = CRM_Utils_Rule
::$ruleName($dateVal);
2154 // format date and time to default.
2155 if ($ruleName == 'dateTime') {
2156 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", "", $dateVal), '%Y%m%d%H%i');
2157 // hack to add seconds
2160 $formattedDate = $dateVal;
2164 return $formattedDate;
2168 * Function to return days of the month.
2172 public static function getCalendarDayOfMonth() {
2174 for ($i = 1; $i <= 31; $i++
) {
2177 $month[$i] = $i . ' / Last day of month';
2184 * Convert a relative date format to an api field.
2186 * @param array $params
2187 * @param string $dateField
2188 * @param bool $isDatePicker
2189 * Non datepicker fields are deprecated. Exterminate Exterminate.
2190 * (but for now handle them).
2192 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2193 if (!empty($params[$dateField . '_relative'])) {
2194 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2195 unset($params[$dateField . '_relative']);
2197 if (!empty($params[$dateField . '_low'])) {
2198 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2199 unset($params[$dateField . '_low']);
2201 if (!empty($params[$dateField . '_high'])) {
2202 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2203 unset($params[$dateField . '_high']);
2205 if (empty($dates)) {
2208 if (empty($dates[0])) {
2209 $params[$dateField] = ['<=' => $dates[1]];
2211 elseif (empty($dates[1])) {
2212 $params[$dateField] = ['>=' => $dates[0]];
2215 $params[$dateField] = ['BETWEEN' => $dates];
2220 * Print out a date object in specified format in local timezone
2222 * @param DateTimeObject $dateObject
2223 * @param string $format
2226 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2227 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2228 $dateObject->setTimezone($systemTimeZone);
2229 return $dateObject->format($format);