Since: 5.5

class DateTimeImmutable implements DateTimeInterface (View source)

Representation of date and time.

This class behaves the same as DateTime except new objects are returned when modification methods such as DateTime::modify are called.

Methods

__construct(string $datetime = "now", null|DateTimeZone $timezone = null)

(PHP 8 >=8.3.0)

add(DateInterval $interval)

(PHP 5 >=5.5.0)
Adds an amount of days, months, years, hours, minutes and seconds

static DateTimeImmutable|false
createFromFormat(string $format, string $datetime, null|DateTimeZone $timezone = null)

(PHP 5 >=5.5.0)
Returns new DateTimeImmutable object formatted according to the specified format

createFromMutable(DateTime $object)

(PHP 5 >=5.6.0)
Returns new DateTimeImmutable object encapsulating the given DateTime object

static array|false
getLastErrors()

(PHP 5 >=5.5.0)
Returns the warnings and errors

modify(string $modifier)

(PHP 8 >=8.3.0)
Alters the timestamp

__set_state(array $array)

(PHP 5 >=5.5.0)
The __set_state handler

setDate(int $year, int $month, int $day)

(PHP 5 >=5.5.0)
Sets the date

setISODate(int $year, int $week, int $dayOfWeek = 1)

(PHP 5 >=5.5.0)
Sets the ISO date

setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0)

(PHP 5 >=5.5.0)
Sets the time

setTimestamp(int $timestamp)

(PHP 5 >=5.5.0)
Sets the date and time based on an Unix timestamp

setTimezone(DateTimeZone $timezone)

(PHP 5 >=5.5.0)
Sets the time zone

sub(DateInterval $interval)

(PHP 5 >=5.5.0)
Subtracts an amount of days, months, years, hours, minutes and seconds

diff(DateTimeInterface $targetObject, bool $absolute = false)

(PHP 5 >=5.5.0)
Returns the difference between two DateTime objects

string
format(string $format)

(PHP 5 >=5.5.0)
Returns date formatted according to given format

int|false
getOffset()

(PHP 5 >=5.5.0)
Returns the timezone offset

int
getTimestamp()

(PHP 5 >=5.5.0)
Gets the Unix timestamp

DateTimeZone|false
getTimezone()

(PHP 5 >=5.5.0)
Return time zone relative to given DateTime

void
__wakeup()

(PHP 5 >=5.5.0)
The __wakeup handler

createFromInterface(DateTimeInterface $object)

Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object

array
__serialize()

Serialize a DateTime

void
__unserialize(array $data)

Unserialize an Datetime

createFromTimestamp(int|float $timestamp)

Creates an instance from a Unix timestamp

int
getMicrosecond()

Gets the microsecond part of the Unix timestamp

setMicrosecond(int $microsecond)

Sets microsecond part of the time

Details

__construct(string $datetime = "now", null|DateTimeZone $timezone = null)

(PHP 8 >=8.3.0)

Parameters

string $datetime

[optional]

A date/time string. Valid formats are explained in https://php.net/manual/en/datetime.formats.php Date and Time Formats.

Enter 'now' here to obtain the current time when using the $timezone parameter.

null|DateTimeZone $timezone

[optional]

A https://php.net/manual/en/class.datetimezone.php DateTimeZone object representing the timezone of $datetime.

If $timezone is omitted, the current timezone will be used.

Note:

The $timezone parameter and the current timezone are ignored when the $datetime parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).

Exceptions

DateMalformedStringException

DateTimeImmutable add(DateInterval $interval)

(PHP 5 >=5.5.0)
Adds an amount of days, months, years, hours, minutes and seconds

Parameters

DateInterval $interval

A DateInterval object

Return Value

DateTimeImmutable

Returns a new DateTimeImmutable object with the modified data.

static DateTimeImmutable|false createFromFormat(string $format, string $datetime, null|DateTimeZone $timezone = null)

(PHP 5 >=5.5.0)
Returns new DateTimeImmutable object formatted according to the specified format

Parameters

string $format

The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the date can be used. All fields are initialised with the current date/time. In most cases you would want to reset these to "zero" (the Unix epoch, 1970-01-01 00:00:00 UTC). You do that by including the ! character as first character in your format, or | as your last. Please see the documentation for each character below for more information. The format is parsed from left to right, which means that in some situations the order in which the format characters are present affects the result. In the case of z (the day of the year), it is required that a year has already been parsed, for example through the Y or y characters. Letters that are used for parsing numbers allow a wide range of values, outside of what the logical range would be. For example, the d (day of the month) accepts values in the range from 00 to 99. The only constraint is on the amount of digits. The date/time parser's overflow mechanism is used when out-of-range values are given. The examples below show some of this behaviour. This also means that the data parsed for a format letter is greedy, and will read up to the amount of digits its format allows for. That can then also mean that there are no longer enough characters in the datetime string for following format characters. An example on this page also illustrates this issue. The following characters are recognized in the format parameter string format character Description Example parsable values Day --- --- d and j Day of the month, 2 digits with or without leading zeros 01 to 31 or 1 to 31. (2 digit numbers higher than the number of days in the month are accepted, in which case they will make the month overflow. For example using 33 with January, means February 2nd) D and l A textual representation of a day Mon through Sun or Sunday through Saturday. If the day name given is different than the day name belonging to a parsed (or default) date is different, then an overflow occurs to the next date with the given day name. See the examples below for an explanation. S English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. st, nd, rd or th. z The day of the year (starting from 0); must be preceded by Y or y. 0 through 365. (3 digit numbers higher than the numbers in a year are accepted, in which case they will make the year overflow. For example using 366 with 2022, means January 2nd, 2023) Month --- --- F and M A textual representation of a month, such as January or Sept January through December or Jan through Dec m and n Numeric representation of a month, with or without leading zeros 01 through 12 or 1 through 12. (2 digit numbers higher than 12 are accepted, in which case they will make the year overflow. For example using 13 means January in the next year) Year --- --- X and x A full numeric representation of a year, up to 19 digits, optionally prefixed by

  • or - Examples: 0055, 787, 1999, -2003, +10191 Y A full numeric representation of a year, up to 4 digits Examples: 25 (same as 0025), 787, 1999, 2003 y A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) Examples: 99 or 03 (which will be interpreted as 1999 and 2003, respectively) Time --- --- a and A Ante meridiem and Post meridiem am or pm g and h 12-hour format of an hour with or without leading zero 1 through 12 or 01 through 12 (2 digit numbers higher than 12 are accepted, in which case they will make the day overflow. For example using 14 means 02 in the next AM/PM period) G and H 24-hour format of an hour with or without leading zeros 0 through 23 or 00 through 23 (2 digit numbers higher than 24 are accepted, in which case they will make the day overflow. For example using 26 means 02:00 the next day) i Minutes with leading zeros 00 to 59. (2 digit numbers higher than 59 are accepted, in which case they will make the hour overflow. For example using 66 means :06 the next hour) s Seconds, with leading zeros 00 through 59 (2 digit numbers higher than 59 are accepted, in which case they will make the minute overflow. For example using 90 means :30 the next minute) v Fraction in milliseconds (up to three digits) Example: 12 (0.12 seconds), 345 (0.345 seconds) u Fraction in microseconds (up to six digits) Example: 45 (0.45 seconds), 654321 (0.654321 seconds) Timezone --- --- e, O, p, P and T Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation Examples: UTC, GMT, Atlantic/Azores or +0200 or +02:00 or EST, MDT Full Date/Time --- --- U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) Example: 1292177455 Whitespace and Separators --- --- (space) Zero or more spaces, tabs, NBSP (U+A0), or NNBSP (U+202F) characters Example: "\t", " " # One of the following separation symbol: ;, :, /, ., ,, -, ( or ) Example: / ;, :, /, ., ,, -, ( or ) The specified character. Example: - ? A random byte Example: ^ (Be aware that for UTF-8 characters you might need more than one ?. In this case, using is probably what you want instead) Random bytes until the next separator or digit Example: in Y--d with the string 2009-aWord-08 will match aWord ! Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values ( 0 for hour, minute, second and fraction, 1 for month and day, 1970 for year and the default timezone) Without !, all fields will be set to the current date and time. | Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values if they have not been parsed yet Y-m-d| will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0. + If this format specifier is present, trailing data in the string will not cause an error, but a warning instead Use DateTimeImmutable::getLastErrors to find out whether trailing data was present. Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with DateTimeImmutable::getLastErrors. To include literal characters in format, you have to escape them with a backslash (). If format does not contain the character ! then portions of the generated date/time which are not specified in format will be set to the current system time. If format contains the character !, then portions of the generated date/time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch. If any time character is parsed, then all other time-related fields are set to "0", unless also parsed. The Unix epoch is 1970-01-01 00:00:00 UTC.
string $datetime

String representing the time.

null|DateTimeZone $timezone [optional]

Return Value

DateTimeImmutable|false

Returns a new DateTimeImmutable instance or false on failure.

Exceptions

ValueError

static DateTimeImmutable createFromMutable(DateTime $object)

(PHP 5 >=5.6.0)
Returns new DateTimeImmutable object encapsulating the given DateTime object

Parameters

DateTime $object

The mutable DateTime object that you want to convert to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date time and timezone information.

Return Value

DateTimeImmutable

returns a new DateTimeImmutable instance.

static array|false getLastErrors()

(PHP 5 >=5.5.0)
Returns the warnings and errors

Return Value

array|false

Returns array containing info about warnings and errors.

DateTimeImmutable|false modify(string $modifier)

(PHP 8 >=8.3.0)
Alters the timestamp

Parameters

string $modifier

A date/time string. Valid formats are explained in https://php.net/manual/en/datetime.formats.php Date and Time Formats.

Return Value

DateTimeImmutable|false

Returns the newly created object or false on failure.

Exceptions

DateMalformedStringException

static DateTimeImmutable __set_state(array $array)

(PHP 5 >=5.5.0)
The __set_state handler

Parameters

array $array

Initialization array.

Return Value

DateTimeImmutable

Returns a new instance of a https://php.net/manual/en/class.datetimeimmutable.php DateTimeImmutable object.

DateTimeImmutable setDate(int $year, int $month, int $day)

(PHP 5 >=5.5.0)
Sets the date

Parameters

int $year

Year of the date.

int $month

Month of the date.

int $day

Day of the date.

Return Value

DateTimeImmutable

Returns the https://php.net/manual/en/class.datetimeimmutable.php DateTimeImmutable object for method chaining. Prior to PHP 8.1, FALSE was returned on failure.

DateTimeImmutable setISODate(int $year, int $week, int $dayOfWeek = 1)

(PHP 5 >=5.5.0)
Sets the ISO date

Parameters

int $year

Year of the date.

int $week

Week of the date.

int $dayOfWeek

[optional]

Offset from the first day of the week.

Return Value

DateTimeImmutable

Returns the https://php.net/manual/en/class.datetimeimmutable.php DateTimeImmutable object for method chaining. Prior to PHP 8.1, FALSE was returned on failure.

DateTimeImmutable setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0)

(PHP 5 >=5.5.0)
Sets the time

Parameters

int $hour

Hour of the time.

int $minute

Minute of the time.

int $second

[optional]

Second of the time.

int $microsecond

[optional]

Microseconds of the time. Added since 7.1

Return Value

DateTimeImmutable

Returns the https://php.net/manual/en/class.datetimeimmutable.php DateTimeImmutable object for method chaining. Prior to PHP 8.1, FALSE was returned on failure.

DateTimeImmutable setTimestamp(int $timestamp)

(PHP 5 >=5.5.0)
Sets the date and time based on an Unix timestamp

Parameters

int $timestamp

Unix timestamp representing the date.

Return Value

DateTimeImmutable

Returns the https://php.net/manual/en/class.datetimeimmutable.php DateTimeImmutable object for method chaining. Prior to PHP 8.1, FALSE was returned on failure.

DateTimeImmutable setTimezone(DateTimeZone $timezone)

(PHP 5 >=5.5.0)
Sets the time zone

Parameters

DateTimeZone $timezone

A https://php.net/manual/en/class.datetimezone.php DateTimeZone object representing the desired time zone.

Return Value

DateTimeImmutable

Returns the https://php.net/manual/en/class.datetimeimmutable.php DateTimeImmutable object for method chaining. Prior to PHP 8.1, FALSE was returned on failure.

DateTimeImmutable sub(DateInterval $interval)

(PHP 5 >=5.5.0)
Subtracts an amount of days, months, years, hours, minutes and seconds

Parameters

DateInterval $interval

A https://php.net/manual/en/class.dateinterval.php DateInterval object

Return Value

DateTimeImmutable

Returns a new DateTimeImmutable object with the modified data.

Exceptions

DateInvalidOperationException

DateInterval diff(DateTimeInterface $targetObject, bool $absolute = false)

(PHP 5 >=5.5.0)
Returns the difference between two DateTime objects

Parameters

DateTimeInterface $targetObject

The date to compare to.

bool $absolute

Should the interval be forced to be positive?

Return Value

DateInterval

The https://secure.php.net/manual/en/class.dateinterval.php DateInterval} object representing the difference between the two dates.

string format(string $format)

(PHP 5 >=5.5.0)
Returns date formatted according to given format

Parameters

string $format

Format accepted by https://php.net/manual/en/function.date.php date().

Return Value

string

Returns the formatted date string on success. Prior to PHP 8.1, FALSE was returned on failure.

int|false getOffset()

(PHP 5 >=5.5.0)
Returns the timezone offset

Return Value

int|false

Returns the timezone offset in seconds from UTC on success. Prior to PHP 8.0, FALSE was returned on failure.

int getTimestamp()

(PHP 5 >=5.5.0)
Gets the Unix timestamp

Return Value

int

Returns the Unix timestamp representing the date.

DateTimeZone|false getTimezone()

(PHP 5 >=5.5.0)
Return time zone relative to given DateTime

Return Value

DateTimeZone|false

Returns a https://php.net/manual/en/class.datetimezone.php DateTimeZone object on success or FALSE on failure.

void __wakeup()

(PHP 5 >=5.5.0)
The __wakeup handler

Return Value

void

Initializes a DateTime object.

static DateTimeImmutable createFromInterface(DateTimeInterface $object)

Since: 8.0

Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object

Parameters

DateTimeInterface $object

The DateTimeInterface object that needs to be converted to an immutable version. This object is not modified, but instead a new DateTimeImmutable object is created containing the same date, time, and timezone information.

Return Value

DateTimeImmutable

Returns a new DateTimeImmutable instance.

array __serialize()

Serialize a DateTime

The __serialize() handler.

Return Value

array

The serialized representation of the DateTime object.

void __unserialize(array $data)

Unserialize an Datetime

The __unserialize() handler.

Parameters

array $data

The serialized DateTime.

Return Value

void

static DateTimeImmutable createFromTimestamp(int|float $timestamp)

Since: 8.4

Creates an instance from a Unix timestamp

Parameters

int|float $timestamp

Return Value

DateTimeImmutable

Exceptions

DateRangeError

int getMicrosecond()

Since: 8.4

Gets the microsecond part of the Unix timestamp

Return Value

int

DateTimeImmutable setMicrosecond(int $microsecond)

Since: 8.4

Sets microsecond part of the time

Returns a new DateTimeImmutable object constructed from the old one, with modified microsecond part.

Parameters

int $microsecond

Return Value

DateTimeImmutable

Exceptions

DateRangeError