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 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
174 // First day of the week
175 $firstDay = Civi
::settings()->get('weekBegins');
177 \Civi
::$statics[__CLASS__
][$key] = [];
178 for ($i = $firstDay; count(\Civi
::$statics[__CLASS__
][$key]) < 7; $i = $i > 5 ?
0 : $i +
1) {
179 \Civi
::$statics[__CLASS__
][$key][$i] = $days[$i];
182 return \Civi
::$statics[__CLASS__
][$key];
186 * Return full weekday names according to the locale.
188 * Array will be in localized order according to 'weekBegins' setting,
189 * but array keys will always match to:
195 * 0-based array with full weekday names
198 public static function getFullWeekdayNames() {
199 $key = 'fullDays_' . \CRM_Core_I18n
::getLocale();
200 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
205 3 => ts('Wednesday'),
210 // First day of the week
211 $firstDay = Civi
::settings()->get('weekBegins');
213 \Civi
::$statics[__CLASS__
][$key] = [];
214 for ($i = $firstDay; count(\Civi
::$statics[__CLASS__
][$key]) < 7; $i = $i > 5 ?
0 : $i +
1) {
215 \Civi
::$statics[__CLASS__
][$key][$i] = $days[$i];
218 return \Civi
::$statics[__CLASS__
][$key];
222 * Return abbreviated month names according to the locale.
227 * 1-based array with abbreviated month names
230 public static function &getAbbrMonthNames($month = FALSE) {
231 $key = 'abbrMonthNames_' . \CRM_Core_I18n
::getLocale();
232 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
233 \Civi
::$statics[__CLASS__
][$key] = [
249 return \Civi
::$statics[__CLASS__
][$key][$month];
251 return \Civi
::$statics[__CLASS__
][$key];
255 * Return full month names according to the locale.
258 * 1-based array with full month names
261 public static function &getFullMonthNames() {
262 $key = 'fullMonthNames_' . \CRM_Core_I18n
::getLocale();
263 if (empty(\Civi
::$statics[__CLASS__
][$key])) {
264 // Not relying on strftime because it depends on the operating system
265 // and most people will not have a non-US locale configured out of the box
266 // Ignoring other date names for now, since less visible by default
267 \Civi
::$statics[__CLASS__
][$key] = [
276 9 => ts('September'),
278 11 => ts('November'),
279 12 => ts('December'),
283 return \Civi
::$statics[__CLASS__
][$key];
287 * @param string $string
291 public static function unixTime($string) {
292 if (empty($string)) {
295 $parsedDate = date_parse($string);
296 return mktime(CRM_Utils_Array
::value('hour', $parsedDate),
297 CRM_Utils_Array
::value('minute', $parsedDate),
299 CRM_Utils_Array
::value('month', $parsedDate),
300 CRM_Utils_Array
::value('day', $parsedDate),
301 CRM_Utils_Array
::value('year', $parsedDate)
306 * Create a date and time string in a provided format.
307 * %A - Full day name ('Saturday'..'Sunday')
308 * %a - abbreviated day name ('Sat'..'Sun')
309 * %b - abbreviated month name ('Jan'..'Dec')
310 * %B - full month name ('January'..'December')
311 * %d - day of the month as a decimal number, 0-padded ('01'..'31')
312 * %e - day of the month as a decimal number, blank-padded (' 1'..'31')
313 * %E - day of the month as a decimal number ('1'..'31')
314 * %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th')
315 * %H - hour in 24-hour format, 0-padded ('00'..'23')
316 * %I - hour in 12-hour format, 0-padded ('01'..'12')
317 * %k - hour in 24-hour format, blank-padded (' 0'..'23')
318 * %l - hour in 12-hour format, blank-padded (' 1'..'12')
319 * %m - month as a decimal number, 0-padded ('01'..'12')
320 * %M - minute, 0-padded ('00'..'60')
321 * %p - lowercase ante/post meridiem ('am', 'pm')
322 * %P - uppercase ante/post meridiem ('AM', 'PM')
323 * %Y - year as a decimal number including the century ('2005')
325 * @param string $dateString
326 * Date and time in 'YYYY-MM-DD hh:mm:ss' format.
327 * @param string $format
329 * @param array $dateParts
330 * An array with the desired date parts.
333 * the $format-formatted $date
335 public static function customFormat($dateString, $format = NULL, $dateParts = NULL) {
336 // 1-based (January) month names arrays
337 $abbrMonths = self
::getAbbrMonthNames();
338 $fullMonths = self
::getFullMonthNames();
339 $fullWeekdayNames = self
::getFullWeekdayNames();
340 $abbrWeekdayNames = self
::getAbbrWeekdayNames();
343 $config = CRM_Core_Config
::singleton();
346 if (array_intersect(['h', 'H'], $dateParts)) {
347 $format = $config->dateformatDatetime
;
349 elseif (array_intersect(['d', 'j'], $dateParts)) {
350 $format = $config->dateformatFull
;
352 elseif (array_intersect(['m', 'M'], $dateParts)) {
353 $format = $config->dateformatPartial
;
356 $format = $config->dateformatYear
;
360 if (strpos(($dateString ??
''), '-')) {
361 $month = (int) substr($dateString, 5, 2);
362 $day = (int) substr($dateString, 8, 2);
365 $month = (int) substr(($dateString ??
''), 4, 2);
366 $day = (int) substr(($dateString ??
''), 6, 2);
369 if (strlen(($dateString ??
'')) > 10) {
370 $format = $config->dateformatDatetime
;
373 $format = $config->dateformatFull
;
375 elseif ($month > 0) {
376 $format = $config->dateformatPartial
;
379 $format = $config->dateformatYear
;
384 if (!CRM_Utils_System
::isNull($dateString)) {
385 if (strpos($dateString, '-')) {
386 $year = (int) substr($dateString, 0, 4);
387 $month = (int) substr($dateString, 5, 2);
388 $day = (int) substr($dateString, 8, 2);
390 $hour24 = (int) substr($dateString, 11, 2);
391 $minute = (int) substr($dateString, 14, 2);
392 $second = (int) substr($dateString, 17, 2);
395 $year = (int) substr($dateString, 0, 4);
396 $month = (int) substr($dateString, 4, 2);
397 $day = (int) substr($dateString, 6, 2);
399 $hour24 = (int) substr($dateString, 8, 2);
400 $minute = (int) substr($dateString, 10, 2);
401 $second = (int) substr($dateString, 12, 2);
404 $dayInt = date('w', strtotime($dateString));
406 if ($day %
10 == 1 and $day != 11) {
409 elseif ($day %
10 == 2 and $day != 12) {
412 elseif ($day %
10 == 3 and $day != 13) {
433 $hour12 = $hour24 - 12;
439 '%A' => $fullWeekdayNames[$dayInt] ??
NULL,
440 '%a' => $abbrWeekdayNames[$dayInt] ??
NULL,
441 '%b' => $abbrMonths[$month] ??
NULL,
442 '%B' => $fullMonths[$month] ??
NULL,
443 '%d' => $day > 9 ?
$day : '0' . $day,
444 '%e' => $day > 9 ?
$day : ' ' . $day,
447 '%H' => $hour24 > 9 ?
$hour24 : '0' . $hour24,
448 '%h' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
449 '%I' => $hour12 > 9 ?
$hour12 : '0' . $hour12,
450 '%k' => $hour24 > 9 ?
$hour24 : ' ' . $hour24,
451 '%l' => $hour12 > 9 ?
$hour12 : ' ' . $hour12,
452 '%m' => $month > 9 ?
$month : '0' . $month,
453 '%M' => $minute > 9 ?
$minute : '0' . $minute,
454 '%i' => $minute > 9 ?
$minute : '0' . $minute,
455 '%p' => strtolower($type),
458 '%s' => str_pad($second, 2, 0, STR_PAD_LEFT
),
459 '%S' => str_pad($second, 2, 0, STR_PAD_LEFT
),
462 return strtr($format, $date);
468 * Format the field according to the site's preferred date format.
470 * This is likely to look something like December 31st, 2020.
472 * @param string $date
476 public static function formatDateOnlyLong(string $date):string {
477 return CRM_Utils_Date
::customFormat($date, Civi
::settings()->get('dateformatFull'));
481 * Wrapper for customFormat that takes a timestamp
483 * @param int $timestamp
484 * Date and time in timestamp format.
485 * @param string $format
487 * @param array $dateParts
488 * An array with the desired date parts.
491 * the $format-formatted $date
493 public static function customFormatTs($timestamp, $format = NULL, $dateParts = NULL) {
494 return CRM_Utils_Date
::customFormat(date("Y-m-d H:i:s", $timestamp), $format, $dateParts);
498 * Converts the date/datetime from MySQL format to ISO format
500 * @param string $mysql
501 * Date/datetime in MySQL format.
504 * date/datetime in ISO format
506 public static function mysqlToIso($mysql) {
507 $year = substr(($mysql ??
''), 0, 4);
508 $month = substr(($mysql ??
''), 4, 2);
509 $day = substr(($mysql ??
''), 6, 2);
510 $hour = substr(($mysql ??
''), 8, 2);
511 $minute = substr(($mysql ??
''), 10, 2);
512 $second = substr(($mysql ??
''), 12, 2);
538 * Converts the date/datetime from ISO format to MySQL format
539 * Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was
540 * used to update an object with a date field was used. The DAO now checks for a '-' in date field strings
541 * & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
544 * Date/datetime in ISO format.
547 * date/datetime in MySQL format
549 public static function isoToMysql($iso) {
550 $dropArray = ['-' => '', ':' => '', ' ' => ''];
551 return strtr(($iso ??
''), $dropArray);
555 * Converts the any given date to default date format.
557 * @param array $params
558 * Has given date-format.
559 * @param int $dateType
561 * @param string $dateParam
566 public static function convertToDefaultDate(&$params, $dateType, $dateParam) {
570 if (!empty($params[$dateParam])) {
571 // suppress hh:mm or hh:mm:ss if it exists CRM-7957
572 $value = preg_replace("/(\s(([01]\d)|[2][0-3])(:([0-5]\d)){1,2})$/", "", $params[$dateParam]);
577 if (!preg_match('/^\d\d\d\d-?(\d|\d\d)-?(\d|\d\d)$/', $value)) {
583 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d$/', $value)) {
589 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d$/', $value)) {
595 if (!preg_match('/^[A-Za-z]*.[ \t]?\d\d\,[ \t]?\d\d\d\d$/', $value)) {
601 if (!preg_match('/^\d\d-[A-Za-z]{3}.*-\d\d$/', $value) && !preg_match('/^\d\d[-\/]\d\d[-\/]\d\d$/', $value)) {
607 if (!preg_match('/^(\d|\d\d)[-\/](\d|\d\d)[-\/]\d\d\d\d/', $value)) {
613 if ($dateType == 1) {
614 $formattedDate = explode("-", $value);
615 if (count($formattedDate) == 3) {
616 $year = (int) $formattedDate[0];
617 $month = (int) $formattedDate[1];
618 $day = (int) $formattedDate[2];
620 elseif (count($formattedDate) == 1 && (strlen($value) == 8)) {
628 if ($dateType == 2 ||
$dateType == 4) {
629 $formattedDate = explode("/", $value);
630 if (count($formattedDate) != 3) {
631 $formattedDate = explode("-", $value);
633 if (count($formattedDate) == 3) {
634 $year = (int) $formattedDate[2];
635 $month = (int) $formattedDate[0];
636 $day = (int) $formattedDate[1];
642 if ($dateType == 8) {
643 $dateArray = explode(' ', $value);
645 $dateArray[1] = (int) substr($dateArray[1], 0, 2);
648 $fullMonths = self
::getFullMonthNames();
649 foreach ($fullMonths as $key => $val) {
650 if (strtolower($dateArray[0]) == strtolower($val)) {
656 $abbrMonths = self
::getAbbrMonthNames();
657 foreach ($abbrMonths as $key => $val) {
658 if (strtolower(trim($dateArray[0], ".")) == strtolower($val)) {
664 $year = (int) $dateArray[2];
665 $day = (int) $dateArray[1];
666 $month = (int) $monthInt;
668 if ($dateType == 16) {
669 $dateArray = explode('-', $value);
670 if (count($dateArray) != 3) {
671 $dateArray = explode('/', $value);
674 if (count($dateArray) == 3) {
676 $fullMonths = self
::getFullMonthNames();
677 foreach ($fullMonths as $key => $val) {
678 if (strtolower($dateArray[1]) == strtolower($val)) {
684 $abbrMonths = self
::getAbbrMonthNames();
685 foreach ($abbrMonths as $key => $val) {
686 if (strtolower(trim($dateArray[1], ".")) == strtolower($val)) {
693 $monthInt = $dateArray[1];
696 $year = (int) $dateArray[2];
697 $day = (int) $dateArray[0];
698 $month = (int) $monthInt;
704 if ($dateType == 32) {
705 $formattedDate = explode("/", $value);
706 if (count($formattedDate) == 3) {
707 $year = (int) $formattedDate[2];
708 $month = (int) $formattedDate[1];
709 $day = (int) $formattedDate[0];
716 $month = ($month < 10) ?
"0" . "$month" : $month;
717 $day = ($day < 10) ?
"0" . "$day" : $day;
721 $year = substr($now['year'], 0, 2) * 100 +
$year;
722 if ($year > ($now['year'] +
5)) {
725 elseif ($year <= ($now['year'] - 95)) {
730 if ($params[$dateParam]) {
731 $params[$dateParam] = "$year$month$day";
733 // if month is invalid return as error
734 if ($month !== '00' && $month <= 12) {
741 * Translate a TTL to a concrete expiration time.
743 * @param null|int|DateInterval $ttl
744 * @param int $default
745 * The value to use if $ttl is not specified (NULL).
747 * Timestamp (seconds since epoch).
748 * @throws \CRM_Utils_Cache_InvalidArgumentException
750 public static function convertCacheTtlToExpires($ttl, $default) {
756 return time() +
$ttl;
758 elseif ($ttl instanceof DateInterval
) {
759 return date_add(new DateTime(), $ttl)->getTimestamp();
762 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
769 * @param null|int|DateInterval $ttl
770 * @param int $default
771 * The value to use if $ttl is not specified (NULL).
773 * Seconds until expiration.
774 * @throws \CRM_Utils_Cache_InvalidArgumentException
776 public static function convertCacheTtl($ttl, $default) {
780 elseif (is_int($ttl)) {
783 elseif ($ttl instanceof DateInterval
) {
784 return date_add(new DateTime(), $ttl)->getTimestamp() - time();
787 throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL");
792 * @param int|false|null $timeStamp
794 * @return bool|string
796 public static function currentDBDate($timeStamp = NULL) {
797 return $timeStamp ?
date('YmdHis', $timeStamp) : date('YmdHis');
806 public static function overdue($date, $now = NULL) {
807 $mysqlDate = self
::isoToMysql($date);
809 $now = self
::currentDBDate();
812 $now = self
::isoToMysql($now);
815 return !(strtotime($mysqlDate) >= strtotime($now));
819 * Get customized today.
821 * This function is used for getting customized today. To get
822 * actuall today pass 'dayParams' as null. or else pass the day,
823 * month, year values as array values
824 * Example: $dayParams = array(
825 * 'day' => '25', 'month' => '10',
826 * 'year' => '2007' );
828 * @param array $dayParams of the day, month, year.
829 * Array of the day, month, year.
831 * @param string $format
832 * Expected date format( default.
833 * format is 2007-12-21 )
836 * Return the customized today's date (Y-m-d)
838 public static function getToday($dayParams = NULL, $format = "Y-m-d") {
839 if (is_null($dayParams) ||
empty($dayParams)) {
840 $today = date($format);
843 $today = date($format, mktime(0, 0, 0,
854 * Find whether today's date lies in
857 * @param date $startDate
858 * Start date for the range.
859 * @param date $endDate
860 * End date for the range.
863 * true if today's date is in the given date range
865 public static function getRange($startDate, $endDate) {
866 $today = date("Y-m-d");
867 $mysqlStartDate = self
::isoToMysql($startDate);
868 $mysqlEndDate = self
::isoToMysql($endDate);
869 $mysqlToday = self
::isoToMysql($today);
871 if ((isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate) && ($mysqlToday <= $mysqlEndDate))) {
874 elseif ((isset($mysqlStartDate) && !isset($mysqlEndDate)) && (($mysqlToday >= $mysqlStartDate))) {
877 elseif ((!isset($mysqlStartDate) && isset($mysqlEndDate)) && (($mysqlToday <= $mysqlEndDate))) {
884 * Get start date and end from
885 * the given relative term and unit
887 * @param string $relative Relative format in the format term.unit.
890 * @param string $from
892 * @param string $fromTime
893 * @param string $toTime
896 * start date, end date
898 public static function getFromTo($relative, $from = NULL, $to = NULL, $fromTime = NULL, $toTime = '235959') {
900 list($term, $unit) = explode('.', $relative, 2);
901 $dateRange = self
::relativeToAbsolute($term, $unit);
902 $from = substr(($dateRange['from'] ??
''), 0, 8);
903 $to = substr(($dateRange['to'] ??
''), 0, 8);
904 // @todo fix relativeToAbsolute & add tests
905 // relativeToAbsolute returns 8 char date strings
906 // or 14 char date + time strings.
907 // We should use those. However, it turns out to be unreliable.
908 // e.g. this.week does NOT return 235959 for 'from'
909 // so our defaults are more reliable.
910 // Currently relativeToAbsolute only supports 'whole' days so that is ok
913 $from = self
::processDate($from, $fromTime);
914 $to = self
::processDate($to, $toTime);
920 * Calculate Age in Years if greater than one year else in months.
922 * @param date $birthDate
924 * @param date $targetDate
925 * Target Date. (show age on specific date)
928 * array $results contains years or months
930 public static function calculateAge($birthDate, $targetDate = NULL) {
932 $formatedBirthDate = CRM_Utils_Date
::customFormat($birthDate, '%Y-%m-%d');
934 $bDate = explode('-', $formatedBirthDate);
935 $birthYear = $bDate[0];
936 $birthMonth = $bDate[1];
937 $birthDay = $bDate[2];
938 $targetDate = strtotime($targetDate ??
date('Y-m-d'));
940 $year_diff = date("Y", $targetDate) - $birthYear;
942 // don't calculate age CRM-3143
943 if ($birthYear == '1902') {
946 switch ($year_diff) {
948 $month = (12 - $birthMonth) +
date("m", $targetDate);
950 if (date("d", $targetDate) < $birthDay) {
953 $results['months'] = $month;
955 elseif ($month == 12 && (date("d", $targetDate) < $birthDay)) {
956 $results['months'] = $month - 1;
959 $results['years'] = $year_diff;
964 $month = date("m", $targetDate) - $birthMonth;
965 $results['months'] = $month;
969 $results['years'] = $year_diff;
970 if ((date("m", $targetDate) < $birthMonth) ||
(date("m", $targetDate) == $birthMonth) && (date("d", $targetDate) < $birthDay)) {
979 * Calculate next payment date according to provided unit & interval
981 * @param string $unit
982 * Frequency unit like year,month, week etc.
984 * @param int $interval
985 * Frequency interval.
988 * Start date of pledge.
990 * @param bool $dontCareTime
993 * contains new date with added interval
995 public static function intervalAdd($unit, $interval, $date, $dontCareTime = FALSE) {
996 if (is_array($date)) {
997 $hour = $date['H'] ??
'00';
998 $minute = $date['i'] ??
'00';
999 $second = $date['s'] ??
'00';
1000 $month = $date['M'] ??
NULL;
1001 $day = $date['d'] ??
NULL;
1002 $year = $date['Y'] ??
NULL;
1005 extract(date_parse($date));
1007 $date = mktime($hour, $minute, $second, $month, $day, $year);
1010 $date = mktime($hour, $minute, $second, $month, $day, $year +
$interval);
1014 $date = mktime($hour, $minute, $second, $month +
$interval, $day, $year);
1018 $interval = $interval * 7;
1019 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1023 $date = mktime($hour, $minute, $second, $month, $day +
$interval, $year);
1027 $date = mktime($hour, $minute, $second +
$interval, $month, $day, $year);
1031 $scheduleDate = explode("-", date("n-j-Y-H-i-s", $date));
1034 $date['M'] = $scheduleDate[0];
1035 $date['d'] = $scheduleDate[1];
1036 $date['Y'] = $scheduleDate[2];
1037 if ($dontCareTime == FALSE) {
1038 $date['H'] = $scheduleDate[3];
1039 $date['i'] = $scheduleDate[4];
1040 $date['s'] = $scheduleDate[5];
1046 * Get the smarty view presentation mapping for the given format.
1048 * Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy'
1049 * they should be rendered using a longer date format. This is likely as much to
1050 * do with the earlier date widget being unable to handle some formats as usablity.
1051 * However, we continue to respect this.
1054 * Given format ( eg 'M Y', 'Y M' ).
1056 * @return string|null
1057 * Smarty translation of the date format. Null is also valid and is translated
1058 * according to the available parts at the smarty layer.
1060 public static function getDateFieldViewFormat($format) {
1061 $supportableFormats = [
1062 'mm/dd' => '%B %E%f',
1063 'dd-mm' => '%E%f %B',
1067 'dd/mm/yy' => '%E%f %B %Y',
1070 return array_key_exists($format, $supportableFormats) ?
$supportableFormats[$format] : self
::pickBestSmartyFormat($format);
1074 * Pick the smarty format from settings that best matches the time string we have.
1076 * For view purposes we historically use the setting that most closely matches the data
1077 * in the format from our settings, as opposed to the setting configured for the field.
1082 public static function pickBestSmartyFormat($format) {
1083 if (stristr($format, 'h')) {
1084 return Civi
::settings()->get('dateformatDatetime');
1086 if (stristr($format, 'd') ||
stristr($format, 'j')) {
1087 return Civi
::settings()->get('dateformatFull');
1089 if (stristr($format, 'm')) {
1090 return Civi
::settings()->get('dateformatPartial');
1092 return Civi
::settings()->get('dateformatYear');
1096 * Map date plugin and actual format that is used by PHP.
1100 public static function datePluginToPHPFormats() {
1101 $dateInputFormats = [
1102 "mm/dd/yy" => 'm/d/Y',
1103 "dd/mm/yy" => 'd/m/Y',
1104 "yy-mm-dd" => 'Y-m-d',
1105 "dd-mm-yy" => 'd-m-Y',
1106 "dd.mm.yy" => 'd.m.Y',
1108 "M d, yy" => 'M j, Y',
1109 "d M yy" => 'j M Y',
1110 "MM d, yy" => 'F j, Y',
1111 "d MM yy" => 'j F Y',
1112 "DD, d MM yy" => 'l, j F Y',
1120 return $dateInputFormats;
1124 * Resolves the given relative time interval into finite time limits.
1126 * @param string $relativeTerm
1127 * Relative time frame: this, previous, previous_1.
1129 * Frequency unit like year, month, week etc.
1132 * start date and end date for the relative time frame
1134 public static function relativeToAbsolute($relativeTerm, $unit) {
1136 $from = $to = $dateRange = [];
1137 $from['H'] = $from['i'] = $from['s'] = 0;
1138 $relativeTermParts = explode('_', $relativeTerm);
1139 $relativeTermPrefix = $relativeTermParts[0];
1140 $relativeTermSuffix = $relativeTermParts[1] ??
'';
1144 switch ($relativeTerm) {
1146 $from['M'] = $from['d'] = 1;
1149 $to['Y'] = $from['Y'] = $now['year'] - 1;
1152 case 'previous_before':
1153 $from['M'] = $from['d'] = 1;
1156 $to['Y'] = $from['Y'] = $now['year'] - 2;
1160 $from['M'] = $from['d'] = 1;
1163 $from['Y'] = $now['year'] - 2;
1164 $to['Y'] = $now['year'] - 1;
1170 $to['Y'] = $now['year'] - 1;
1175 $from['M'] = $from['d'] = 1;
1176 $from['Y'] = $now['year'];
1180 case 'greater_previous':
1183 $from['Y'] = $now['year'] - 1;
1188 $to['d'] = $now['mday'];
1189 $to['M'] = $now['mon'];
1190 $to['Y'] = $now['year'];
1192 $to['i'] = $to['s'] = 59;
1193 $from = self
::intervalAdd('year', -1, $to);
1194 $from = self
::intervalAdd('second', 1, $from);
1198 $from['M'] = $from['d'] = 1;
1199 $from['Y'] = $now['year'];
1201 $to['i'] = $to['s'] = 59;
1202 $to['d'] = $now['mday'];
1203 $to['M'] = $now['mon'];
1204 $to['Y'] = $now['year'];
1208 $to['d'] = $now['mday'];
1209 $to['M'] = $now['mon'];
1210 $to['Y'] = $now['year'];
1212 $to['i'] = $to['s'] = 59;
1213 $from = self
::intervalAdd('year', -2, $to);
1214 $from = self
::intervalAdd('second', 1, $from);
1218 $to['d'] = $now['mday'];
1219 $to['M'] = $now['mon'];
1220 $to['Y'] = $now['year'];
1222 $to['i'] = $to['s'] = 59;
1223 $from = self
::intervalAdd('year', -3, $to);
1224 $from = self
::intervalAdd('second', 1, $from);
1230 $to['Y'] = $now['year'];
1235 $from['M'] = $from['d'] = 1;
1238 $to['Y'] = $from['Y'] = $now['year'] +
1;
1242 $from['d'] = $now['mday'];
1243 $from['M'] = $now['mon'];
1244 $from['Y'] = $now['year'];
1245 $to['d'] = $now['mday'] - 1;
1246 $to['M'] = $now['mon'];
1247 $to['Y'] = $now['year'] +
1;
1251 switch ($relativeTermPrefix) {
1254 $to['d'] = $now['mday'];
1255 $to['M'] = $now['mon'];
1256 $to['Y'] = $now['year'];
1258 $to['i'] = $to['s'] = 59;
1259 $from = self
::intervalAdd('year', -$relativeTermSuffix, $to);
1260 $from = self
::intervalAdd('second', 1, $from);
1264 $from['d'] = $from['M'] = 1;
1267 $to['Y'] = $from['Y'] = $now['year'];
1268 if (is_numeric($relativeTermSuffix)) {
1269 $from['Y'] -= ($relativeTermSuffix - 1);
1278 $config = CRM_Core_Config
::singleton();
1279 $from['d'] = $config->fiscalYearStart
['d'];
1280 $from['M'] = $config->fiscalYearStart
['M'];
1281 $fYear = self
::calculateFiscalYear($from['d'], $from['M']);
1282 switch ($relativeTermPrefix) {
1284 $from['Y'] = $fYear;
1285 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1286 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1287 $to['d'] = $fiscalEnd['2'];
1288 $to['M'] = $fiscalEnd['1'];
1289 $to['Y'] = $fiscalEnd['0'];
1291 $to['i'] = $to['s'] = 59;
1292 if (is_numeric($relativeTermSuffix)) {
1293 $from = self
::intervalAdd('year', (-$relativeTermSuffix), $to);
1294 $from = self
::intervalAdd('second', 1, $from);
1299 if (!is_numeric($relativeTermSuffix)) {
1300 $from['Y'] = ($relativeTermSuffix === 'before') ?
$fYear - 2 : $fYear - 1;
1301 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1302 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1303 $to['d'] = $fiscalEnd['2'];
1304 $to['M'] = $fiscalEnd['1'];
1305 $to['Y'] = $fiscalEnd['0'];
1307 $to['i'] = $to['s'] = 59;
1310 $from['Y'] = $fYear - $relativeTermSuffix;
1311 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1312 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1313 $to['d'] = $fiscalEnd['2'];
1314 $to['M'] = $fiscalEnd['1'];
1317 $to['i'] = $to['s'] = 59;
1322 $from['Y'] = $fYear +
1;
1323 $fiscalYear = mktime(0, 0, 0, $from['M'], $from['d'] - 1, $from['Y'] +
1);
1324 $fiscalEnd = explode('-', date("Y-m-d", $fiscalYear));
1325 $to['d'] = $fiscalEnd['2'];
1326 $to['M'] = $fiscalEnd['1'];
1327 $to['Y'] = $fiscalEnd['0'];
1333 switch ($relativeTerm) {
1336 $quarter = ceil($now['mon'] / 3);
1338 $from['M'] = (3 * $quarter) - 2;
1339 $to['M'] = 3 * $quarter;
1340 $to['Y'] = $from['Y'] = $now['year'];
1341 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1346 $quarter = ceil($now['mon'] / 3);
1347 $quarter = $quarter - $difference;
1349 if ($quarter <= 0) {
1354 $from['M'] = (3 * $quarter) - 2;
1355 $to['M'] = 3 * $quarter;
1356 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1357 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1360 case 'previous_before':
1362 $quarter = ceil($now['mon'] / 3);
1363 $quarter = $quarter - $difference;
1365 if ($quarter <= 0) {
1370 $from['M'] = (3 * $quarter) - 2;
1371 $to['M'] = 3 * $quarter;
1372 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1373 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1378 $quarter = ceil($now['mon'] / 3);
1379 $current_quarter = $quarter;
1380 $quarter = $quarter - $difference;
1382 if ($quarter <= 0) {
1387 $from['M'] = (3 * $quarter) - 2;
1388 switch ($current_quarter) {
1390 $to['M'] = (4 * $quarter);
1394 $to['M'] = (4 * $quarter) +
3;
1398 $to['M'] = (4 * $quarter) +
2;
1402 $to['M'] = (4 * $quarter) +
1;
1405 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1406 if ($to['M'] > 12) {
1407 $to['M'] = 3 * ($quarter - 3);
1408 $to['Y'] = $now['year'];
1410 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1414 $quarter = ceil($now['mon'] / 3) - 1;
1416 if ($quarter <= 0) {
1420 $to['M'] = 3 * $quarter;
1421 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1422 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1427 $quarter = ceil($now['mon'] / 3);
1429 $from['M'] = (3 * $quarter) - 2;
1430 $from['Y'] = $now['year'];
1434 case 'greater_previous':
1435 $quarter = ceil($now['mon'] / 3) - 1;
1437 if ($quarter <= 0) {
1441 $from['M'] = 3 * $quarter;
1442 $from['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1443 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1448 $to['d'] = $now['mday'];
1449 $to['M'] = $now['mon'];
1450 $to['Y'] = $now['year'];
1452 $to['i'] = $to['s'] = 59;
1453 $from = self
::intervalAdd('day', -90, $to);
1454 $from = self
::intervalAdd('second', 1, $from);
1458 $quarter = ceil($now['mon'] / 3);
1460 $from['M'] = (3 * $quarter) - 2;
1461 $from['Y'] = $now['year'];
1462 $to['d'] = $now['mday'];
1463 $to['M'] = $now['mon'];
1464 $to['Y'] = $now['year'];
1466 $to['i'] = $to['s'] = 59;
1470 $quarter = ceil($now['mon'] / 3);
1471 $to['M'] = 3 * $quarter;
1472 $to['Y'] = $now['year'];
1473 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $now['year']));
1480 $quarter = ceil($now['mon'] / 3);
1481 $quarter = $quarter - $difference;
1484 $now['year'] = $now['year'] +
1;
1487 if ($quarter <= 0) {
1492 $from['M'] = (3 * $quarter) - 2;
1493 $to['M'] = 3 * $quarter;
1494 $to['Y'] = $from['Y'] = $now['year'] - $subtractYear;
1495 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1499 $from['d'] = $now['mday'];
1500 $from['M'] = $now['mon'];
1501 $from['Y'] = $now['year'];
1503 $from['i'] = $to['s'] = 00;
1504 $to = self
::intervalAdd('day', 90, $from);
1505 $to = self
::intervalAdd('second', -1, $to);
1509 if ($relativeTermPrefix === 'ending') {
1510 $to['d'] = $now['mday'];
1511 $to['M'] = $now['mon'];
1512 $to['Y'] = $now['year'];
1514 $to['i'] = $to['s'] = 59;
1515 $from = self
::intervalAdd('month', -($relativeTermSuffix * 3), $to);
1516 $from = self
::intervalAdd('second', 1, $from);
1522 switch ($relativeTerm) {
1525 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1526 $from['M'] = $to['M'] = $now['mon'];
1527 $from['Y'] = $to['Y'] = $now['year'];
1532 if ($now['mon'] == 1) {
1533 $from['M'] = $to['M'] = 12;
1534 $from['Y'] = $to['Y'] = $now['year'] - 1;
1537 $from['M'] = $to['M'] = $now['mon'] - 1;
1538 $from['Y'] = $to['Y'] = $now['year'];
1540 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1543 case 'previous_before':
1545 if ($now['mon'] < 3) {
1546 $from['M'] = $to['M'] = 10 +
$now['mon'];
1547 $from['Y'] = $to['Y'] = $now['year'] - 1;
1550 $from['M'] = $to['M'] = $now['mon'] - 2;
1551 $from['Y'] = $to['Y'] = $now['year'];
1553 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1558 if ($now['mon'] < 3) {
1559 $from['M'] = 10 +
$now['mon'];
1560 $from['Y'] = $now['year'] - 1;
1563 $from['M'] = $now['mon'] - 2;
1564 $from['Y'] = $now['year'];
1567 if ($now['mon'] == 1) {
1569 $to['Y'] = $now['year'] - 1;
1572 $to['M'] = $now['mon'] - 1;
1573 $to['Y'] = $now['year'];
1576 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1580 // before end of past month
1581 if ($now['mon'] == 1) {
1583 $to['Y'] = $now['year'] - 1;
1586 $to['M'] = $now['mon'] - 1;
1587 $to['Y'] = $now['year'];
1590 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1596 $from['M'] = $now['mon'];
1597 $from['Y'] = $now['year'];
1601 case 'greater_previous':
1602 // from end of past month
1603 if ($now['mon'] == 1) {
1605 $from['Y'] = $now['year'] - 1;
1608 $from['M'] = $now['mon'] - 1;
1609 $from['Y'] = $now['year'];
1612 $from['d'] = date('t', mktime(0, 0, 0, $from['M'], 1, $from['Y']));
1617 $to['d'] = $now['mday'];
1618 $to['M'] = $now['mon'];
1619 $to['Y'] = $now['year'];
1621 $to['i'] = $to['s'] = 59;
1622 $from = self
::intervalAdd('day', -60, $to);
1623 $from = self
::intervalAdd('second', 1, $from);
1627 $to['d'] = $now['mday'];
1628 $to['M'] = $now['mon'];
1629 $to['Y'] = $now['year'];
1631 $to['i'] = $to['s'] = 59;
1632 $from = self
::intervalAdd('day', -30, $to);
1633 $from = self
::intervalAdd('second', 1, $from);
1638 $from['M'] = $now['mon'];
1639 $from['Y'] = $now['year'];
1640 $to['d'] = $now['mday'];
1641 $to['M'] = $now['mon'];
1642 $to['Y'] = $now['year'];
1644 $to['i'] = $to['s'] = 59;
1649 $to['Y'] = $now['year'];
1650 $to['M'] = $now['mon'];
1651 $to['d'] = date('t', mktime(0, 0, 0, $now['mon'], 1, $now['year']));
1657 if ($now['mon'] == 12) {
1658 $from['M'] = $to['M'] = 1;
1659 $from['Y'] = $to['Y'] = $now['year'] +
1;
1662 $from['M'] = $to['M'] = $now['mon'] +
1;
1663 $from['Y'] = $to['Y'] = $now['year'];
1665 $to['d'] = date('t', mktime(0, 0, 0, $to['M'], 1, $to['Y']));
1669 $from['d'] = $now['mday'];
1670 $from['M'] = $now['mon'];
1671 $from['Y'] = $now['year'];
1673 $from['i'] = $to['s'] = 00;
1674 $to = self
::intervalAdd('day', 30, $from);
1675 $to = self
::intervalAdd('second', -1, $to);
1679 $from['d'] = $now['mday'];
1680 $from['M'] = $now['mon'];
1681 $from['Y'] = $now['year'];
1683 $from['i'] = $to['s'] = 00;
1684 $to = self
::intervalAdd('day', 60, $from);
1685 $to = self
::intervalAdd('second', -1, $to);
1689 if ($relativeTermPrefix === 'ending') {
1690 $to['d'] = $now['mday'];
1691 $to['M'] = $now['mon'];
1692 $to['Y'] = $now['year'];
1694 $to['i'] = $to['s'] = 59;
1695 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1696 $from = self
::intervalAdd('second', 1, $from);
1702 $weekFirst = Civi
::settings()->get('weekBegins');
1703 $thisDay = $now['wday'];
1704 if ($weekFirst > $thisDay) {
1705 $diffDay = $thisDay - $weekFirst +
7;
1708 $diffDay = $thisDay - $weekFirst;
1710 switch ($relativeTerm) {
1712 $from['d'] = $now['mday'];
1713 $from['M'] = $now['mon'];
1714 $from['Y'] = $now['year'];
1715 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1716 $to = self
::intervalAdd('day', 6, $from);
1720 $from['d'] = $now['mday'];
1721 $from['M'] = $now['mon'];
1722 $from['Y'] = $now['year'];
1723 $from = self
::intervalAdd('day', -1 * ($diffDay) - 7, $from);
1724 $to = self
::intervalAdd('day', 6, $from);
1727 case 'previous_before':
1728 $from['d'] = $now['mday'];
1729 $from['M'] = $now['mon'];
1730 $from['Y'] = $now['year'];
1731 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1732 $to = self
::intervalAdd('day', 6, $from);
1736 $from['d'] = $now['mday'];
1737 $from['M'] = $now['mon'];
1738 $from['Y'] = $now['year'];
1739 $from = self
::intervalAdd('day', -1 * ($diffDay) - 14, $from);
1740 $to = self
::intervalAdd('day', 13, $from);
1744 $to['d'] = $now['mday'];
1745 $to['M'] = $now['mon'];
1746 $to['Y'] = $now['year'];
1747 $to = self
::intervalAdd('day', -1 * ($diffDay) - 1, $to);
1752 $from['d'] = $now['mday'];
1753 $from['M'] = $now['mon'];
1754 $from['Y'] = $now['year'];
1755 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1759 case 'greater_previous':
1760 $from['d'] = $now['mday'];
1761 $from['M'] = $now['mon'];
1762 $from['Y'] = $now['year'];
1763 $from = self
::intervalAdd('day', -1 * ($diffDay) - 1, $from);
1768 $to['d'] = $now['mday'];
1769 $to['M'] = $now['mon'];
1770 $to['Y'] = $now['year'];
1772 $to['i'] = $to['s'] = 59;
1773 $from = self
::intervalAdd('day', -7, $to);
1774 $from = self
::intervalAdd('second', 1, $from);
1778 $from['d'] = $now['mday'];
1779 $from['M'] = $now['mon'];
1780 $from['Y'] = $now['year'];
1781 $from = self
::intervalAdd('day', -1 * ($diffDay), $from);
1782 $to['d'] = $now['mday'];
1783 $to['M'] = $now['mon'];
1784 $to['Y'] = $now['year'];
1786 $to['i'] = $to['s'] = 59;
1790 $to['d'] = $now['mday'];
1791 $to['M'] = $now['mon'];
1792 $to['Y'] = $now['year'];
1794 $to = self
::intervalAdd('day', -1 * ($diffDay) +
6, $to);
1799 $from['d'] = $now['mday'];
1800 $from['M'] = $now['mon'];
1801 $from['Y'] = $now['year'];
1802 $from = self
::intervalAdd('day', -1 * ($diffDay) +
7, $from);
1803 $to = self
::intervalAdd('day', 6, $from);
1807 $from['d'] = $now['mday'];
1808 $from['M'] = $now['mon'];
1809 $from['Y'] = $now['year'];
1811 $from['i'] = $to['s'] = 00;
1812 $to = self
::intervalAdd('day', 7, $from);
1813 $to = self
::intervalAdd('second', -1, $to);
1817 if ($relativeTermPrefix === 'ending') {
1818 $to['d'] = $now['mday'];
1819 $to['M'] = $now['mon'];
1820 $to['Y'] = $now['year'];
1822 $to['i'] = $to['s'] = 59;
1823 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1824 $from = self
::intervalAdd('second', 1, $from);
1830 switch ($relativeTerm) {
1832 $from['d'] = $to['d'] = $now['mday'];
1833 $from['M'] = $to['M'] = $now['mon'];
1834 $from['Y'] = $to['Y'] = $now['year'];
1838 $from['d'] = $now['mday'];
1839 $from['M'] = $now['mon'];
1840 $from['Y'] = $now['year'];
1841 $from = self
::intervalAdd('day', -1, $from);
1842 $to['d'] = $from['d'];
1843 $to['M'] = $from['M'];
1844 $to['Y'] = $from['Y'];
1847 case 'previous_before':
1848 $from['d'] = $now['mday'];
1849 $from['M'] = $now['mon'];
1850 $from['Y'] = $now['year'];
1851 $from = self
::intervalAdd('day', -2, $from);
1852 $to['d'] = $from['d'];
1853 $to['M'] = $from['M'];
1854 $to['Y'] = $from['Y'];
1858 $from['d'] = $to['d'] = $now['mday'];
1859 $from['M'] = $to['M'] = $now['mon'];
1860 $from['Y'] = $to['Y'] = $now['year'];
1861 $from = self
::intervalAdd('day', -2, $from);
1862 $to = self
::intervalAdd('day', -1, $to);
1866 $to['d'] = $now['mday'];
1867 $to['M'] = $now['mon'];
1868 $to['Y'] = $now['year'];
1869 $to = self
::intervalAdd('day', -1, $to);
1874 $from['d'] = $now['mday'];
1875 $from['M'] = $now['mon'];
1876 $from['Y'] = $now['year'];
1881 $to['d'] = $now['mday'];
1882 $to['M'] = $now['mon'];
1883 $to['Y'] = $now['year'];
1884 $to = self
::intervalAdd('day', 1, $to);
1885 $from['d'] = $to['d'];
1886 $from['M'] = $to['M'];
1887 $from['Y'] = $to['Y'];
1891 if ($relativeTermPrefix === 'ending') {
1892 $to['d'] = $now['mday'];
1893 $to['M'] = $now['mon'];
1894 $to['Y'] = $now['year'];
1896 $to['i'] = $to['s'] = 59;
1897 $from = self
::intervalAdd($unit, -$relativeTermSuffix, $to);
1898 $from = self
::intervalAdd('second', 1, $from);
1904 $dateRange['from'] = empty($from) ?
NULL : self
::format($from);
1905 $dateRange['to'] = empty($to) ?
NULL : self
::format($to);
1910 * Calculate current fiscal year based on the fiscal month and day.
1912 * @param int $fyDate
1913 * Fiscal start date.
1915 * @param int $fyMonth
1916 * Fiscal Start Month.
1919 * $fy Current Fiscal Year
1921 public static function calculateFiscalYear($fyDate, $fyMonth) {
1922 $date = date("Y-m-d");
1923 $currentYear = date("Y");
1925 // recalculate the date because month 4::04 make the difference
1926 $fiscalYear = explode('-', date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear)));
1927 $fyDate = $fiscalYear[2];
1928 $fyMonth = $fiscalYear[1];
1929 $fyStartDate = date("Y-m-d", mktime(0, 0, 0, $fyMonth, $fyDate, $currentYear));
1931 if ($fyStartDate > $date) {
1932 $fy = intval(intval($currentYear) - 1);
1935 $fy = intval($currentYear);
1941 * Function to process date, convert to mysql format
1943 * @param string $date
1945 * @param string $time
1947 * @param bool|string $returnNullString 'null' needs to be returned
1948 * so that db oject will set null in db
1949 * @param string $format
1950 * Expected return date format.( default is mysql ).
1953 * date format that is excepted by mysql
1955 public static function processDate($date, $time = NULL, $returnNullString = FALSE, $format = 'YmdHis') {
1958 if ($returnNullString) {
1959 $mysqlDate = 'null';
1962 if (trim($date ??
'')) {
1963 $mysqlDate = date($format, strtotime($date . ' ' . $time));
1970 * Add the metadata about a date field to the field.
1972 * This metadata will work with the call $form->add('datepicker', ...
1974 * @param array $fieldMetaData
1975 * @param array $field
1979 public static function addDateMetadataToField($fieldMetaData, $field) {
1980 if (isset($fieldMetaData['html'])) {
1981 $field['html_type'] = $fieldMetaData['html']['type'];
1982 if ($field['html_type'] === 'Select Date') {
1983 if (!isset($field['date_format'])) {
1984 $dateAttributes = CRM_Core_SelectValues
::date($fieldMetaData['html']['formatType'], NULL, NULL, NULL, 'Input');
1985 $field['start_date_years'] = $dateAttributes['minYear'];
1986 $field['end_date_years'] = $dateAttributes['maxYear'];
1987 $field['date_format'] = $dateAttributes['format'];
1988 $field['is_datetime_field'] = TRUE;
1989 $field['time_format'] = $dateAttributes['time'];
1990 $field['smarty_view_format'] = $dateAttributes['smarty_view_format'];
1992 $field['datepicker']['extra'] = self
::getDatePickerExtra($field);
1993 $field['datepicker']['attributes'] = self
::getDatePickerAttributes($field);
2000 * Get the fields required for the 'extra' parameter when adding a datepicker.
2002 * @param array $field
2006 public static function getDatePickerExtra($field) {
2008 if (isset($field['date_format'])) {
2009 $extra['date'] = $field['date_format'];
2010 $extra['time'] = $field['time_format'];
2012 $thisYear = date('Y');
2013 if (isset($field['start_date_years'])) {
2014 $extra['minDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['start_date_years']) . ' years'));
2016 if (isset($field['end_date_years'])) {
2017 $extra['maxDate'] = date('Y-m-d', strtotime('-' . ($thisYear - $field['end_date_years']) . ' years'));
2023 * Get the attributes parameters required for datepicker.
2025 * @param array $field
2029 * Array ready to pass to $this->addForm('datepicker' as attributes.
2031 public static function getDatePickerAttributes(&$field) {
2034 'start_date_years' => 'minYear',
2035 'end_date_years' => 'maxYear',
2036 'date_format' => 'format',
2038 foreach ($dateAttributes as $dateAttribute => $mapTo) {
2039 if (isset($field[$dateAttribute])) {
2040 $attributes[$mapTo] = $field[$dateAttribute];
2047 * Function to convert mysql to date plugin format.
2049 * @param string $mysqlDate
2052 * @param null $formatType
2053 * @param null $format
2054 * @param null $timeFormat
2059 public static function setDateDefaults($mysqlDate = NULL, $formatType = NULL, $format = NULL, $timeFormat = NULL) {
2060 // if date is not passed assume it as today
2062 $mysqlDate = date('Y-m-d G:i:s');
2065 $config = CRM_Core_Config
::singleton();
2067 // get actual format
2068 $params = ['name' => $formatType];
2070 CRM_Core_DAO
::commonRetrieve('CRM_Core_DAO_PreferencesDate', $params, $values);
2072 if ($values['date_format']) {
2073 $format = $values['date_format'];
2076 if (isset($values['time_format'])) {
2077 $timeFormat = $values['time_format'];
2081 $dateFormat = 'm/d/Y';
2082 $date = date($dateFormat, strtotime($mysqlDate));
2085 $timeFormat = $config->timeInputFormat
;
2088 $actualTimeFormat = "g:iA";
2089 $appendZeroLength = 7;
2090 if ($timeFormat > 1) {
2091 $actualTimeFormat = "G:i";
2092 $appendZeroLength = 5;
2095 $time = date($actualTimeFormat, strtotime($mysqlDate));
2097 // need to append zero for hours < 10
2098 if (strlen($time) < $appendZeroLength) {
2099 $time = '0' . $time;
2102 return [$date, $time];
2106 * Function get date format.
2108 * @param string $formatType
2109 * Date name e.g. birth.
2113 public static function getDateFormat($formatType = NULL) {
2116 $format = CRM_Core_DAO
::getFieldValue('CRM_Core_DAO_PreferencesDate',
2117 $formatType, 'date_format', 'name'
2122 $config = CRM_Core_Config
::singleton();
2123 $format = $config->dateInputFormat
;
2129 * Date formatting for imports where date format is specified.
2131 * Note this is used for imports (only) because the importer can
2132 * specify the format.
2134 * Tests are in CRM_Utils_DateTest::testFormatDate
2137 * Date string as entered.
2139 * One of the constants like CRM_Core_Form_Date::DATE_yyyy_mm_dd.
2141 * @return null|string
2143 public static function formatDate($date, $dateType) {
2148 // 1. first convert date to default format.
2149 // 2. append time to default formatted date (might be removed during format)
2150 // 3. validate date / date time.
2151 // 4. If date and time then convert to default date time format.
2154 $dateParams = [$dateKey => $date];
2156 if (CRM_Utils_Date
::convertToDefaultDate($dateParams, $dateType, $dateKey)) {
2157 $dateVal = $dateParams[$dateKey];
2158 if ($dateType == 1) {
2160 // The seconds part of this regex is not quite right - but it does succeed
2161 // in clarifying whether there is a time component or not - which is all it is meant
2163 if (preg_match('/(\s(([01]\d)|[2][0-3]):([0-5]\d):?[0-5]?\d?)$/', $date, $matches)) {
2164 if (strpos($date, '-') !== FALSE) {
2165 $dateVal .= array_shift($matches);
2167 if (!CRM_Utils_Rule
::dateTime($dateVal)) {
2170 $dateVal = CRM_Utils_Date
::customFormat(preg_replace("/(:|\s)?/", '', $dateVal), '%Y%m%d%H%i%s');
2176 return CRM_Utils_Rule
::date($dateVal) ?
$dateVal : NULL;
2183 * Function to return days of the month.
2187 public static function getCalendarDayOfMonth() {
2189 for ($i = 1; $i <= 31; $i++
) {
2192 $month[$i] = $i . ' / Last day of month';
2199 * Convert a relative date format to an api field.
2201 * @param array $params
2202 * @param string $dateField
2203 * @param bool $isDatePicker
2204 * Non datepicker fields are deprecated. Exterminate Exterminate.
2205 * (but for now handle them).
2207 public static function convertFormDateToApiFormat(&$params, $dateField, $isDatePicker = TRUE) {
2208 if (!empty($params[$dateField . '_relative'])) {
2209 $dates = CRM_Utils_Date
::getFromTo($params[$dateField . '_relative'], NULL, NULL);
2210 unset($params[$dateField . '_relative']);
2212 if (!empty($params[$dateField . '_low'])) {
2213 $dates[0] = $isDatePicker ?
$params[$dateField . '_low'] : date('Y-m-d H:i:s', strtotime($params[$dateField . '_low']));
2214 unset($params[$dateField . '_low']);
2216 if (!empty($params[$dateField . '_high'])) {
2217 $dates[1] = $isDatePicker ?
$params[$dateField . '_high'] : date('Y-m-d 23:59:59', strtotime($params[$dateField . '_high']));
2218 unset($params[$dateField . '_high']);
2220 if (empty($dates)) {
2223 if (empty($dates[0])) {
2224 $params[$dateField] = ['<=' => $dates[1]];
2226 elseif (empty($dates[1])) {
2227 $params[$dateField] = ['>=' => $dates[0]];
2230 $params[$dateField] = ['BETWEEN' => $dates];
2235 * Print out a date object in specified format in local timezone
2237 * @param DateTimeObject $dateObject
2238 * @param string $format
2241 public static function convertDateToLocalTime($dateObject, $format = 'YmdHis') {
2242 $systemTimeZone = new DateTimeZone(CRM_Core_Config
::singleton()->userSystem
->getTimeZoneString());
2243 $dateObject->setTimezone($systemTimeZone);
2244 return $dateObject->format($format);
2248 * Check if the value returned by a date picker has a date section (ie: includes
2249 * a '-' character) if it includes a time section (ie: includes a ':').
2251 * @param string $value
2252 * A date/time string input from a datepicker value.
2255 * TRUE if valid, FALSE if there is a time without a date.
2257 public static function datePickerValueWithTimeHasDate($value) {
2258 // If there's no : (time) or a : and a - (date) then return true
2260 strpos($value, ':') === FALSE
2261 ||
strpos($value, ':') !== FALSE && strpos($value, '-') !== FALSE
2266 * Validate start and end dates entered on a form to make sure they are
2267 * logical. Expects the form keys to be start_date and end_date.
2269 * @param string $startFormKey
2270 * The form element key of the 'start date'
2271 * @param string $startValue
2272 * The value of the 'start date'
2273 * @param string $endFormKey
2274 * The form element key of the 'end date'
2275 * @param string $endValue
2276 * The value of the 'end date'
2278 * @return array|bool
2279 * TRUE if valid, an array of the erroneous form key, and error message to
2282 public static function validateStartEndDatepickerInputs($startFormKey, $startValue, $endFormKey, $endValue) {
2284 // Check date as well as time is set
2285 if (!empty($startValue) && !self
::datePickerValueWithTimeHasDate($startValue)) {
2286 return ['key' => $startFormKey, 'message' => ts('Please enter a date as well as a time.')];
2288 if (!empty($endValue) && !self
::datePickerValueWithTimeHasDate($endValue)) {
2289 return ['key' => $endFormKey, 'message' => ts('Please enter a date as well as a time.')];
2292 // Check end date is after start date
2293 if (!empty($startValue) && !empty($endValue) && $endValue < $startValue) {
2294 return ['key' => $endFormKey, 'message' => ts('The end date should be after the start date.')];