CRM_Utils_Date
in package
Date utilties
Table of Contents
Constants
- DATE_dd_mm_yyyy = 32
- Date input formats.
- DATE_dd_mon_yy = 16
- Date input formats.
- DATE_mm_dd_yy = 2
- Date input formats.
- DATE_mm_dd_yyyy = 4
- Date input formats.
- DATE_Month_dd_yyyy = 8
- Date input formats.
- DATE_yyyy_mm_dd = 1
- Date input formats.
Methods
- addDateMetadataToField() : array<string|int, mixed>
- Add the metadata about a date field to the field.
- calculateAge() : array<string|int, mixed>
- Calculate Age in Years if greater than one year else in months.
- calculateFiscalYear() : int
- Calculate current fiscal year based on the fiscal month and day.
- convertCacheTtl() : int
- Normalize a TTL.
- convertCacheTtlToExpires() : int
- Translate a TTL to a concrete expiration time.
- convertDateToLocalTime() : string
- Print out a date object in specified format in local timezone
- convertFormDateToApiFormat() : mixed
- Convert a relative date format to an api field.
- convertToDefaultDate() : bool
- Converts the any given date to default date format.
- currentDBDate() : bool|string
- customFormat() : string
- Create a date and time string in a provided format.
- customFormatTs() : string
- Wrapper for customFormat that takes a timestamp
- datePickerValueWithTimeHasDate() : bool
- Check if the value returned by a date picker has a date section (ie: includes a '-' character) if it includes a time section (ie: includes a ':').
- datePluginToPHPFormats() : array<string|int, mixed>
- Map date plugin and actual format that is used by PHP.
- format() : string
- Format a date by padding it with leading '0'.
- formatDate() : null|string
- Date formatting for imports where date format is specified.
- formatDateOnlyLong() : string
- Format the field according to the site's preferred date format.
- getAbbrMonthNames() : array<string|int, mixed>|string
- Return abbreviated month names according to the locale.
- getAbbrWeekdayNames() : array<string|int, mixed>
- Return abbreviated weekday names according to the locale.
- getAnniversarySql() : string
- Sql expression to calculate the upcoming anniversary of a given date.
- getAvailableInputFormats() : array<string|int, mixed>
- Get the available input formats.
- getCalendarDayOfMonth() : array<string|int, mixed>
- Function to return days of the month.
- getDateFieldViewFormat() : string|null
- Get the smarty view presentation mapping for the given format.
- getDateFormat() : string
- Function get date format.
- getDatePickerAttributes() : array<string|int, mixed>
- Get the attributes parameters required for datepicker.
- getDatePickerExtra() : array<string|int, mixed>
- Get the fields required for the 'extra' parameter when adding a datepicker.
- getFromTo() : array<string|int, mixed>
- Get start date and end from the given relative term and unit
- getFullMonthNames() : array<string|int, mixed>
- Return full month names according to the locale.
- getFullWeekdayNames() : array<string|int, mixed>
- Return full weekday names according to the locale.
- getRange() : bool
- Find whether today's date lies in the given range
- getToday() : string
- Get customized today.
- intervalAdd() : array<string|int, mixed>
- Calculate next payment date according to provided unit & interval
- isoToMysql() : string
- Converts the date/datetime from ISO format to MySQL format Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was used to update an object with a date field was used. The DAO now checks for a '-' in date field strings & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
- mysqlToIso() : string
- Converts the date/datetime from MySQL format to ISO format
- overdue() : bool
- pickBestSmartyFormat() : mixed
- Pick the smarty format from settings that best matches the time string we have.
- processDate() : string
- Function to process date, convert to mysql format
- relativeToAbsolute() : array<string|int, mixed>
- Resolves the given relative time interval into finite time limits.
- setDateDefaults() : array<string|int, mixed>
- Function to convert mysql to date plugin format.
- unixTime() : int
- validateStartEndDatepickerInputs() : array<string|int, mixed>|bool
- Validate start and end dates entered on a form to make sure they are logical. Expects the form keys to be start_date and end_date.
Constants
DATE_dd_mm_yyyy
Date input formats.
public
mixed
DATE_dd_mm_yyyy
= 32
For example a user selecting DATE_dd_mm_yyyy
in the context of an import is
saying that they want the dates they are importing to be converted from dd_mm_yyy format.
DATE_dd_mon_yy
Date input formats.
public
mixed
DATE_dd_mon_yy
= 16
For example a user selecting DATE_dd_mm_yyyy
in the context of an import is
saying that they want the dates they are importing to be converted from dd_mm_yyy format.
DATE_mm_dd_yy
Date input formats.
public
mixed
DATE_mm_dd_yy
= 2
For example a user selecting DATE_dd_mm_yyyy
in the context of an import is
saying that they want the dates they are importing to be converted from dd_mm_yyy format.
DATE_mm_dd_yyyy
Date input formats.
public
mixed
DATE_mm_dd_yyyy
= 4
For example a user selecting DATE_dd_mm_yyyy
in the context of an import is
saying that they want the dates they are importing to be converted from dd_mm_yyy format.
DATE_Month_dd_yyyy
Date input formats.
public
mixed
DATE_Month_dd_yyyy
= 8
For example a user selecting DATE_dd_mm_yyyy
in the context of an import is
saying that they want the dates they are importing to be converted from dd_mm_yyy format.
DATE_yyyy_mm_dd
Date input formats.
public
mixed
DATE_yyyy_mm_dd
= 1
For example a user selecting DATE_dd_mm_yyyy
in the context of an import is
saying that they want the dates they are importing to be converted from dd_mm_yyy format.
Methods
addDateMetadataToField()
Add the metadata about a date field to the field.
public
static addDateMetadataToField(array<string|int, mixed> $fieldMetaData, array<string|int, mixed> $field) : array<string|int, mixed>
This metadata will work with the call $form->add('datepicker', ...
Parameters
- $fieldMetaData : array<string|int, mixed>
- $field : array<string|int, mixed>
Return values
array<string|int, mixed>calculateAge()
Calculate Age in Years if greater than one year else in months.
public
static calculateAge(Date $birthDate[, Date $targetDate = NULL ]) : array<string|int, mixed>
Parameters
- $birthDate : Date
-
Birth Date.
- $targetDate : Date = NULL
-
Target Date. (show age on specific date)
Return values
array<string|int, mixed> —array $results contains years or months
calculateFiscalYear()
Calculate current fiscal year based on the fiscal month and day.
public
static calculateFiscalYear(int $fyDate, int $fyMonth) : int
Parameters
- $fyDate : int
-
Fiscal start date.
- $fyMonth : int
-
Fiscal Start Month.
Return values
int —$fy Current Fiscal Year
convertCacheTtl()
Normalize a TTL.
public
static convertCacheTtl(null|int|DateInterval $ttl, int $default) : int
Parameters
- $ttl : null|int|DateInterval
- $default : int
-
The value to use if $ttl is not specified (NULL).
Tags
Return values
int —Seconds until expiration.
convertCacheTtlToExpires()
Translate a TTL to a concrete expiration time.
public
static convertCacheTtlToExpires(null|int|DateInterval $ttl, int $default) : int
Parameters
- $ttl : null|int|DateInterval
- $default : int
-
The value to use if $ttl is not specified (NULL).
Tags
Return values
int —Timestamp (seconds since epoch).
convertDateToLocalTime()
Print out a date object in specified format in local timezone
public
static convertDateToLocalTime(DateTimeInterface $dateObject[, string $format = 'YmdHis' ]) : string
Parameters
- $dateObject : DateTimeInterface
- $format : string = 'YmdHis'
Return values
stringconvertFormDateToApiFormat()
Convert a relative date format to an api field.
public
static convertFormDateToApiFormat(array<string|int, mixed> &$params, string $dateField[, bool $isDatePicker = TRUE ]) : mixed
Parameters
- $params : array<string|int, mixed>
- $dateField : string
- $isDatePicker : bool = TRUE
-
Non datepicker fields are deprecated. Exterminate Exterminate. (but for now handle them).
convertToDefaultDate()
Converts the any given date to default date format.
public
static convertToDefaultDate(array<string|int, mixed> &$params, int $dateType, string $dateParam) : bool
since 5.70 will be removed around 5.80.
At time of deprecation only usages were in CiviHR & CiviProspect in classes that appeared to be otherwise unmaintained & broken.
Parameters
- $params : array<string|int, mixed>
-
Has given date-format.
- $dateType : int
-
Type of date.
- $dateParam : string
-
Index of params.
Return values
boolcurrentDBDate()
public
static currentDBDate([int|false|null $timeStamp = NULL ]) : bool|string
Parameters
- $timeStamp : int|false|null = NULL
Return values
bool|stringcustomFormat()
Create a date and time string in a provided format.
public
static customFormat(string $dateString[, string $format = NULL ][, array<string|int, mixed> $dateParts = NULL ]) : string
%A - Full day name ('Saturday'..'Sunday') %a - abbreviated day name ('Sat'..'Sun') %b - abbreviated month name ('Jan'..'Dec') %B - full month name ('January'..'December') %d - day of the month as a decimal number, 0-padded ('01'..'31') %e - day of the month as a decimal number, blank-padded (' 1'..'31') %E - day of the month as a decimal number ('1'..'31') %f - English ordinal suffix for the day of the month ('st', 'nd', 'rd', 'th') %H - hour in 24-hour format, 0-padded ('00'..'23') %I - hour in 12-hour format, 0-padded ('01'..'12') %k - hour in 24-hour format, blank-padded (' 0'..'23') %l - hour in 12-hour format, blank-padded (' 1'..'12') %m - month as a decimal number, 0-padded ('01'..'12') %M - minute, 0-padded ('00'..'60') %p - lowercase ante/post meridiem ('am', 'pm') %P - uppercase ante/post meridiem ('AM', 'PM') %Y - year as a decimal number including the century ('2005')
Parameters
- $dateString : string
-
Date and time in 'YYYY-MM-DD hh:mm:ss' format.
- $format : string = NULL
-
The output format.
- $dateParts : array<string|int, mixed> = NULL
-
An array with the desired date parts.
Return values
string —the $format-formatted $date
customFormatTs()
Wrapper for customFormat that takes a timestamp
public
static customFormatTs(int $timestamp[, string $format = NULL ][, array<string|int, mixed> $dateParts = NULL ]) : string
Parameters
- $timestamp : int
-
Date and time in timestamp format.
- $format : string = NULL
-
The output format.
- $dateParts : array<string|int, mixed> = NULL
-
An array with the desired date parts.
Return values
string —the $format-formatted $date
datePickerValueWithTimeHasDate()
Check if the value returned by a date picker has a date section (ie: includes a '-' character) if it includes a time section (ie: includes a ':').
public
static datePickerValueWithTimeHasDate(string $value) : bool
Parameters
- $value : string
-
A date/time string input from a datepicker value.
Return values
bool —TRUE if valid, FALSE if there is a time without a date.
datePluginToPHPFormats()
Map date plugin and actual format that is used by PHP.
public
static datePluginToPHPFormats() : array<string|int, mixed>
Return values
array<string|int, mixed>format()
Format a date by padding it with leading '0'.
public
static format(array<string|int, mixed> $date[, string $separator = '' ][, int|string $invalidDate = 0 ]) : string
Parameters
- $date : array<string|int, mixed>
-
('Y', 'M', 'd').
- $separator : string = ''
-
The separator to use when formatting the date.
- $invalidDate : int|string = 0
-
what to return if the date is invalid
Return values
string —formatted string for date
formatDate()
Date formatting for imports where date format is specified.
public
static formatDate(mixed $date[, int $dateType = self::DATE_yyyy_mm_dd ]) : null|string
Note this is used for imports (only) because the importer can specify the format.
Tests are in CRM_Utils_DateTest::testFormatDate
Parameters
- $date : mixed
-
Date string as entered.
- $dateType : int = self::DATE_yyyy_mm_dd
-
One of the constants like CRM_Utils_Date::DATE_yyyy_mm_dd.
Return values
null|stringformatDateOnlyLong()
Format the field according to the site's preferred date format.
public
static formatDateOnlyLong(string $date) : string
This is likely to look something like December 31st, 2020.
Parameters
- $date : string
Return values
stringgetAbbrMonthNames()
Return abbreviated month names according to the locale.
public
static getAbbrMonthNames([bool|string $month = FALSE ]) : array<string|int, mixed>|string
Parameters
- $month : bool|string = FALSE
-
(deprecated)
Return values
array<string|int, mixed>|string —1-based array with abbreviated month names
getAbbrWeekdayNames()
Return abbreviated weekday names according to the locale.
public
static getAbbrWeekdayNames() : array<string|int, mixed>
Array will be in localized order according to 'weekBegins' setting, but array keys will always match to: 0 => Sun 1 => Mon etc.
Return values
array<string|int, mixed> —0-based array with abbreviated weekday names
getAnniversarySql()
Sql expression to calculate the upcoming anniversary of a given date.
public
static getAnniversarySql(string $dateColumn) : string
The IF() accounts for the possibility that the date has already passed, & so skips to next year. The INTERVAL() functions correctly handle leap years.
Parameters
- $dateColumn : string
Return values
stringgetAvailableInputFormats()
Get the available input formats.
public
static getAvailableInputFormats(bool $isShowTime) : array<string|int, mixed>
These are the formats that this class is able to convert into a standard format provided it knows the input format. These are used when doing an import.
Parameters
- $isShowTime : bool
Return values
array<string|int, mixed>getCalendarDayOfMonth()
Function to return days of the month.
public
static getCalendarDayOfMonth() : array<string|int, mixed>
Return values
array<string|int, mixed>getDateFieldViewFormat()
Get the smarty view presentation mapping for the given format.
public
static getDateFieldViewFormat(mixed $format) : string|null
Historically it was decided that where the view format is 'dd/mm/yy' or 'mm/dd/yy' they should be rendered using a longer date format. This is likely as much to do with the earlier date widget being unable to handle some formats as usablity. However, we continue to respect this.
Parameters
- $format : mixed
-
Given format ( eg 'M Y', 'Y M' ).
Return values
string|null —Smarty translation of the date format. Null is also valid and is translated according to the available parts at the smarty layer.
getDateFormat()
Function get date format.
public
static getDateFormat([string $formatType = NULL ]) : string
Parameters
- $formatType : string = NULL
-
Date name e.g. birth.
Return values
stringgetDatePickerAttributes()
Get the attributes parameters required for datepicker.
public
static getDatePickerAttributes(array<string|int, mixed> &$field) : array<string|int, mixed>
Parameters
- $field : array<string|int, mixed>
-
Field metadata
Return values
array<string|int, mixed> —Array ready to pass to $this->addForm('datepicker' as attributes.
getDatePickerExtra()
Get the fields required for the 'extra' parameter when adding a datepicker.
public
static getDatePickerExtra(array<string|int, mixed> $field) : array<string|int, mixed>
Parameters
- $field : array<string|int, mixed>
Return values
array<string|int, mixed>getFromTo()
Get start date and end from the given relative term and unit
public
static getFromTo(string $relative[, string $from = NULL ][, string $to = NULL ][, string $fromTime = NULL ][, string $toTime = '235959' ]) : array<string|int, mixed>
Parameters
- $relative : string
-
Relative format in the format term.unit. Eg: previous.day
- $from : string = NULL
- $to : string = NULL
- $fromTime : string = NULL
- $toTime : string = '235959'
Return values
array<string|int, mixed> —start date, end date
getFullMonthNames()
Return full month names according to the locale.
public
static getFullMonthNames() : array<string|int, mixed>
Return values
array<string|int, mixed> —1-based array with full month names
getFullWeekdayNames()
Return full weekday names according to the locale.
public
static getFullWeekdayNames() : array<string|int, mixed>
Array will be in localized order according to 'weekBegins' setting, but array keys will always match to: 0 => Sunday 1 => Monday etc.
Return values
array<string|int, mixed> —0-based array with full weekday names
getRange()
Find whether today's date lies in the given range
public
static getRange(Date $startDate, Date $endDate) : bool
Parameters
- $startDate : Date
-
Start date for the range.
- $endDate : Date
-
End date for the range.
Return values
bool —true if today's date is in the given date range
getToday()
Get customized today.
public
static getToday([array<string|int, mixed> $dayParams = NULL ][, string $format = "Y-m-d" ]) : string
This function is used for getting customized today. To get actuall today pass 'dayParams' as null. or else pass the day, month, year values as array values Example: $dayParams = array( 'day' => '25', 'month' => '10', 'year' => '2007' );
Parameters
- $dayParams : array<string|int, mixed> = NULL
-
of the day, month, year. Array of the day, month, year. values.
- $format : string = "Y-m-d"
-
Expected date format( default. format is 2007-12-21 )
Return values
string —Return the customized today's date (Y-m-d)
intervalAdd()
Calculate next payment date according to provided unit & interval
public
static intervalAdd(string $unit, int $interval, array<string|int, mixed> $date[, bool $dontCareTime = FALSE ]) : array<string|int, mixed>
Parameters
- $unit : string
-
Frequency unit like year,month, week etc.
- $interval : int
-
Frequency interval.
- $date : array<string|int, mixed>
-
Start date of pledge.
- $dontCareTime : bool = FALSE
Return values
array<string|int, mixed> —contains new date with added interval
isoToMysql()
Converts the date/datetime from ISO format to MySQL format Note that until CRM-14986/ 4.4.7 this was required whenever the pattern $dao->find(TRUE): $dao->save(); was used to update an object with a date field was used. The DAO now checks for a '-' in date field strings & runs this function if the - appears - meaning it is likely redundant in the form & BAO layers
public
static isoToMysql(string $iso) : string
Parameters
- $iso : string
-
Date/datetime in ISO format.
Return values
string —date/datetime in MySQL format
mysqlToIso()
Converts the date/datetime from MySQL format to ISO format
public
static mysqlToIso(string $mysql) : string
Parameters
- $mysql : string
-
Date/datetime in MySQL format.
Return values
string —date/datetime in ISO format
overdue()
public
static overdue(mixed $date[, null $now = NULL ]) : bool
Parameters
- $date : mixed
- $now : null = NULL
Return values
boolpickBestSmartyFormat()
Pick the smarty format from settings that best matches the time string we have.
public
static pickBestSmartyFormat(mixed $format) : mixed
For view purposes we historically use the setting that most closely matches the data in the format from our settings, as opposed to the setting configured for the field.
Parameters
- $format : mixed
processDate()
Function to process date, convert to mysql format
public
static processDate(string $date[, string $time = NULL ][, bool|string $returnNullString = FALSE ][, string $format = 'YmdHis' ]) : string
Parameters
- $date : string
-
Date string.
- $time : string = NULL
-
Time string.
- $returnNullString : bool|string = FALSE
-
'null' needs to be returned so that db oject will set null in db
- $format : string = 'YmdHis'
-
Expected return date format.( default is mysql ).
Return values
string —date format that is excepted by mysql
relativeToAbsolute()
Resolves the given relative time interval into finite time limits.
public
static relativeToAbsolute(string $relativeTerm, int $unit) : array<string|int, mixed>
Parameters
- $relativeTerm : string
-
Relative time frame: this, previous, previous_1.
- $unit : int
-
Frequency unit like year, month, week etc.
Return values
array<string|int, mixed> —start date and end date for the relative time frame
setDateDefaults()
Function to convert mysql to date plugin format.
public
static setDateDefaults([string $mysqlDate = NULL ][, null $formatType = NULL ][, null $format = NULL ][, null $timeFormat = NULL ]) : array<string|int, mixed>
Parameters
- $mysqlDate : string = NULL
-
Date string.
- $formatType : null = NULL
- $format : null = NULL
- $timeFormat : null = NULL
Return values
array<string|int, mixed> —and time
unixTime()
public
static unixTime(string $string) : int
Parameters
- $string : string
Return values
intvalidateStartEndDatepickerInputs()
Validate start and end dates entered on a form to make sure they are logical. Expects the form keys to be start_date and end_date.
public
static validateStartEndDatepickerInputs(string $startFormKey, string $startValue, string $endFormKey, string $endValue) : array<string|int, mixed>|bool
Parameters
- $startFormKey : string
-
The form element key of the 'start date'
- $startValue : string
-
The value of the 'start date'
- $endFormKey : string
-
The form element key of the 'end date'
- $endValue : string
-
The value of the 'end date'
Return values
array<string|int, mixed>|bool —TRUE if valid, an array of the erroneous form key, and error message to use otherwise.