Fr3nch13/CakePHP Utilities

FrozenDate extends Date
in package
implements I18nDateTimeInterface uses DateFormatTrait

Extends the Date class provided by Chronos.

Adds handy methods and locale-aware formatting helpers

This object provides an immutable variant of

Table of Contents

Interfaces

I18nDateTimeInterface
Interface for date formatting methods shared by both Time & Date.

Properties

$niceFormat  : array<string|int, int>|string|int
The format to use when formatting a time using `Cake\I18n\Date::nice()`
$wordAccuracy  : array<string|int, string>
The format to use when formatting a time using `Date::timeAgoInWords()` and the difference is less than `Date::$wordEnd`
$wordEnd  : string
The end of relative time telling
$wordFormat  : array<string|int, int>|string|int
The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()` and the difference is more than `Cake\I18n\Date::$wordEnd`
$_formatters  : array<string|int, IntlDateFormatter>
In-memory cache of date formatters
$_jsonEncodeFormat  : Closure|array<string|int, int>|string|int
The format to use when converting this object to JSON.
$_toStringFormat  : array<string|int, int>|string|int
The format to use when formatting a time using `Cake\I18n\Date::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.
$defaultLocale  : string|null
The default locale to be used for displaying formatted date strings.
$lenientParsing  : bool
Whether lenient parsing is enabled for IntlDateFormatter.

Methods

__construct()  : mixed
Create a new Date instance.
__debugInfo()  : array<string, mixed>
Returns the data that should be displayed when debugging this object
__toString()  : string
diffForHumans()  : string
Get the difference in a human readable format.
disableLenientParsing()  : void
Enables lenient parsing for locale formats.
enableLenientParsing()  : void
Enables lenient parsing for locale formats.
getDefaultLocale()  : string|null
Gets the default locale.
getDiffFormatter()  : DifferenceFormatterInterface
Get the difference formatter instance.
i18nFormat()  : string|int
Returns a formatted string for this time object using the preferred format and language for the specified locale.
jsonSerialize()  : string|int
Returns a string that should be serialized when converting this object to JSON
lenientParsingEnabled()  : bool
Gets whether locale format parsing is set to lenient.
nice()  : string
Returns a nicely formatted date string for this object.
parseDate()  : static|null
Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
parseDateTime()  : static|null
Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
parseTime()  : static|null
Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.
resetToStringFormat()  : void
Resets the format used to the default when converting an instance of this type to a string
setDefaultLocale()  : void
Sets the default locale.
setDiffFormatter()  : void
Set the difference formatter instance.
setJsonEncodeFormat()  : void
setToStringFormat()  : void
Sets the default format used when type converting instances of this type to string
timeAgoInWords()  : string
Returns either a relative or a formatted absolute date depending on the difference between the current date and this object.
_formatObject()  : string
Returns a translated and localized date string.

Properties

$niceFormat

The format to use when formatting a time using `Cake\I18n\Date::nice()`

public static array<string|int, int>|string|int $niceFormat = [\IntlDateFormatter::MEDIUM, \IntlDateFormatter::NONE]

The format should be either the formatting constants from IntlDateFormatter as described in (https://secure.php.net/manual/en/class.intldateformatter.php) or a pattern as specified in (https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details)

It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.

Tags
see
DateFormatTrait::nice()

$wordAccuracy

The format to use when formatting a time using `Date::timeAgoInWords()` and the difference is less than `Date::$wordEnd`

public static array<string|int, string> $wordAccuracy = ['year' => 'day', 'month' => 'day', 'week' => 'day', 'day' => 'day', 'hour' => 'day', 'minute' => 'day', 'second' => 'day']
Tags
see
Date::timeAgoInWords()

$wordFormat

The format to use when formatting a time using `Cake\I18n\Date::timeAgoInWords()` and the difference is more than `Cake\I18n\Date::$wordEnd`

public static array<string|int, int>|string|int $wordFormat = [\IntlDateFormatter::SHORT, \IntlDateFormatter::NONE]
Tags
see
DateFormatTrait::parseDate()

$_formatters

In-memory cache of date formatters

protected static array<string|int, IntlDateFormatter> $_formatters = []

$_jsonEncodeFormat

The format to use when converting this object to JSON.

protected static Closure|array<string|int, int>|string|int $_jsonEncodeFormat = 'yyyy-MM-dd'

The format should be either the formatting constants from IntlDateFormatter as described in (https://secure.php.net/manual/en/class.intldateformatter.php) or a pattern as specified in (https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details)

It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.

Tags
see
Time::i18nFormat()

$_toStringFormat

The format to use when formatting a time using `Cake\I18n\Date::i18nFormat()` and `__toString`. This format is also used by `parseDateTime()`.

protected static array<string|int, int>|string|int $_toStringFormat = [\IntlDateFormatter::SHORT, -1]

The format should be either the formatting constants from IntlDateFormatter as described in (https://secure.php.net/manual/en/class.intldateformatter.php) or a pattern as specified in (https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details)

It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.

Tags
see
DateFormatTrait::i18nFormat()

$defaultLocale

The default locale to be used for displaying formatted date strings.

protected static string|null $defaultLocale

Use static::setDefaultLocale() and static::getDefaultLocale() instead.

$lenientParsing

Whether lenient parsing is enabled for IntlDateFormatter.

protected static bool $lenientParsing = true

Defaults to true which is the default for IntlDateFormatter.

Methods

__construct()

Create a new Date instance.

public __construct([DateTime|DateTimeImmutable|string|int|null $time = 'now' ][, DateTimeZone|string|null $tz = null ]) : mixed

You can specify the timezone for the $time parameter. This timezone will not be used in any future modifications to the Date instance.

The $timezone parameter is ignored if $time is a DateTimeInterface instance.

Date instances lack time components, however due to limitations in PHP's internal Datetime object the time will always be set to 00:00:00, and the timezone will always be the server local time. Normalizing the timezone allows for subtraction/addition to have deterministic results.

Parameters
$time : DateTime|DateTimeImmutable|string|int|null = 'now'

Fixed or relative time

$tz : DateTimeZone|string|null = null

The timezone in which the date is taken. Ignored if $time is a DateTimeInterface instance.

__debugInfo()

Returns the data that should be displayed when debugging this object

public __debugInfo() : array<string, mixed>
Return values
array<string, mixed>

__toString()

public __toString() : string
Tags
inheritDoc
Return values
string

diffForHumans()

Get the difference in a human readable format.

public diffForHumans([ChronosInterface|null $other = null ][, bool $absolute = false ]) : string

When comparing a value in the past to default now: 1 hour ago 5 months ago

When comparing a value in the future to default now: 1 hour from now 5 months from now

When comparing a value in the past to another value: 1 hour before 5 months before

When comparing a value in the future to another value: 1 hour after 5 months after

Parameters
$other : ChronosInterface|null = null

The datetime to compare with.

$absolute : bool = false

removes time difference modifiers ago, after, etc

Return values
string

disableLenientParsing()

Enables lenient parsing for locale formats.

public static disableLenientParsing() : void

enableLenientParsing()

Enables lenient parsing for locale formats.

public static enableLenientParsing() : void

getDefaultLocale()

Gets the default locale.

public static getDefaultLocale() : string|null
Return values
string|null

The default locale string to be used or null.

i18nFormat()

Returns a formatted string for this time object using the preferred format and language for the specified locale.

public i18nFormat([array<string|int, int>|string|int|null $format = null ][, DateTimeZone|string|null $timezone = null ][, string|null $locale = null ]) : string|int

It is possible to specify the desired format for the string to be displayed. You can either pass IntlDateFormatter constants as the first argument of this function, or pass a full ICU date formatting string as specified in the following resource: https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax.

Additional to IntlDateFormatter constants and date formatting string you can use Time::UNIX_TIMESTAMP_FORMAT to get a unix timestamp

Examples

$time = new Time('2014-04-20 22:10');
$time->i18nFormat(); // outputs '4/20/14, 10:10 PM' for the en-US locale
$time->i18nFormat(\IntlDateFormatter::FULL); // Use the full date and time format
$time->i18nFormat([\IntlDateFormatter::FULL, \IntlDateFormatter::SHORT]); // Use full date but short time format
$time->i18nFormat('yyyy-MM-dd HH:mm:ss'); // outputs '2014-04-20 22:10'
$time->i18nFormat(Time::UNIX_TIMESTAMP_FORMAT); // outputs '1398031800'

You can control the default format used through Time::setToStringFormat().

You can read about the available IntlDateFormatter constants at https://secure.php.net/manual/en/class.intldateformatter.php

If you need to display the date in a different timezone than the one being used for this Time object without altering its internal state, you can pass a timezone string or object as the second parameter.

Finally, should you need to use a different locale for displaying this time object, pass a locale string as the third parameter to this function.

Examples

$time = new Time('2014-04-20 22:10');
$time->i18nFormat(null, null, 'de-DE');
$time->i18nFormat(\IntlDateFormatter::FULL, 'Europe/Berlin', 'de-DE');

You can control the default locale used through Time::setDefaultLocale(). If empty, the default will be taken from the intl.default_locale ini config.

Parameters
$format : array<string|int, int>|string|int|null = null

Format string.

$timezone : DateTimeZone|string|null = null

Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.

$locale : string|null = null

The locale name in which the date should be displayed (e.g. pt-BR)

Return values
string|int

Formatted and translated date string

jsonSerialize()

Returns a string that should be serialized when converting this object to JSON

public jsonSerialize() : string|int
Attributes
#[ReturnTypeWillChange]
Return values
string|int

lenientParsingEnabled()

Gets whether locale format parsing is set to lenient.

public static lenientParsingEnabled() : bool
Return values
bool

nice()

Returns a nicely formatted date string for this object.

public nice([DateTimeZone|string|null $timezone = null ][, string|null $locale = null ]) : string

The format to be used is stored in the static property Time::niceFormat.

Parameters
$timezone : DateTimeZone|string|null = null

Timezone string or DateTimeZone object in which the date will be displayed. The timezone stored for this object will not be changed.

$locale : string|null = null

The locale name in which the date should be displayed (e.g. pt-BR)

Return values
string

Formatted date string

parseDate()

Returns a new Time object after parsing the provided $date string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.

public static parseDate(string $date[, array<string|int, mixed>|string|int|null $format = null ]) : static|null

When no $format is provided, the wordFormat format will be used.

If it was impossible to parse the provided time, null will be returned.

Example:

 $time = Time::parseDate('10/13/2013');
 $time = Time::parseDate('13 Oct, 2013', 'dd MMM, y');
 $time = Time::parseDate('13 Oct, 2013', IntlDateFormatter::SHORT);
Parameters
$date : string

The date string to parse.

$format : array<string|int, mixed>|string|int|null = null

Any format accepted by IntlDateFormatter.

Return values
static|null

parseDateTime()

Returns a new Time object after parsing the provided time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.

public static parseDateTime(string $time[, array<string|int, int>|string|int|null $format = null ][, DateTimeZone|string|null $tz = null ]) : static|null

When no $format is provided, the toString format will be used.

Unlike DateTime, the time zone of the returned instance is always converted to $tz (default time zone if null) even if the $time string specified a time zone. This is a limitation of IntlDateFormatter.

If it was impossible to parse the provided time, null will be returned.

Example:

 $time = Time::parseDateTime('10/13/2013 12:54am');
 $time = Time::parseDateTime('13 Oct, 2013 13:54', 'dd MMM, y H:mm');
 $time = Time::parseDateTime('10/10/2015', [IntlDateFormatter::SHORT, IntlDateFormatter::NONE]);
Parameters
$time : string

The time string to parse.

$format : array<string|int, int>|string|int|null = null

Any format accepted by IntlDateFormatter.

$tz : DateTimeZone|string|null = null

The timezone for the instance

Return values
static|null

parseTime()

Returns a new Time object after parsing the provided $time string based on the passed or configured date time format. This method is locale dependent, Any string that is passed to this function will be interpreted as a locale dependent string.

public static parseTime(string $time[, string|int|null $format = null ]) : static|null

When no $format is provided, the IntlDateFormatter::SHORT format will be used.

If it was impossible to parse the provided time, null will be returned.

Example:

 $time = Time::parseTime('11:23pm');
Parameters
$time : string

The time string to parse.

$format : string|int|null = null

Any format accepted by IntlDateFormatter.

Return values
static|null

resetToStringFormat()

Resets the format used to the default when converting an instance of this type to a string

public static resetToStringFormat() : void

setDefaultLocale()

Sets the default locale.

public static setDefaultLocale([string|null $locale = null ]) : void

Set to null to use IntlDateFormatter default.

Parameters
$locale : string|null = null

The default locale string to be used.

setJsonEncodeFormat()

public static setJsonEncodeFormat(mixed $format) : void
Parameters
$format : mixed
Tags
inheritDoc

setToStringFormat()

Sets the default format used when type converting instances of this type to string

public static setToStringFormat(array<string|int, int>|string|int $format) : void

The format should be either the formatting constants from IntlDateFormatter as described in (https://secure.php.net/manual/en/class.intldateformatter.php) or a pattern as specified in (https://unicode-org.github.io/icu-docs/apidoc/released/icu4c/classSimpleDateFormat.html#details)

It is possible to provide an array of 2 constants. In this case, the first position will be used for formatting the date part of the object and the second position will be used to format the time part.

Parameters
$format : array<string|int, int>|string|int

Format.

timeAgoInWords()

Returns either a relative or a formatted absolute date depending on the difference between the current date and this object.

public timeAgoInWords([array<string, mixed> $options = [] ]) : string

Options:

  • from => another Date object representing the "now" date
  • format => a fall back format if the relative time is longer than the duration specified by end
  • accuracy => Specifies how accurate the date should be described (array)
    • year => The format if years > 0 (default "day")
    • month => The format if months > 0 (default "day")
    • week => The format if weeks > 0 (default "day")
    • day => The format if weeks > 0 (default "day")
  • end => The end of relative date telling
  • relativeString => The printf compatible string when outputting relative date
  • absoluteString => The printf compatible string when outputting absolute date
  • timezone => The user timezone the timestamp should be formatted in.

Relative dates look something like this:

  • 3 weeks, 4 days ago
  • 1 day ago

Default date formatting is d/M/YY e.g: on 18/2/09. Formatting is done internally using i18nFormat, see the method for the valid formatting strings.

The returned string includes 'ago' or 'on' and assumes you'll properly add a word like 'Posted ' before the function output.

NOTE: If the difference is one week or more, the lowest level of accuracy is day.

Parameters
$options : array<string, mixed> = []

Array of options.

Return values
string

Relative time string.

_formatObject()

Returns a translated and localized date string.

protected _formatObject(DateTime|DateTimeImmutable $date, array<string|int, int>|string|int $format, string|null $locale) : string

Implements what IntlDateFormatter::formatObject() is in PHP 5.5+

Parameters
$date : DateTime|DateTimeImmutable

Date.

$format : array<string|int, int>|string|int

Format.

$locale : string|null

The locale name in which the date should be displayed.

Return values
string

        
On this page

Search results