PHP DateTime Class
Unlike date, DateTime
is a class for representing both the date and the time.
class DateTime implements DateTimeInterface { /* Constantaes heredadas constants */ const string DateTimeInterface::ATOM = "Y-m-d\TH:i:sP"; const string DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T"; const string DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO"; const string DateTimeInterface::RFC822 = "D, d M y H:i:s O"; const string DateTimeInterface::RFC850 = "l, d-M-y H:i:s T"; const string DateTimeInterface::RFC1036 = "D, d M y H:i:s O"; const string DateTimeInterface::RFC1123 = "D, d M Y H:i:s O"; const string DateTimeInterface::RFC2822 = "D, d M Y H:i:s O"; const string DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP"; const string DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP"; const string DateTimeInterface::RSS = "D, d M Y H:i:s O"; const string DateTimeInterface::W3C = "Y-m-d\TH:i:sP"; /* Métodos */ public __construct(string $time = "now", DateTimeZone $timezone = null) public add(DateInterval $interval): DateTime public static createFromFormat(string $format, string $time, DateTimeZone $timezone = ?): DateTime public static createFromImmutable(DateTimeImmutable $object): DateTime public static createFromInterface(DateTimeInterface $object): DateTime public static getLastErrors(): array public modify(string $modify): DateTime public static __set_state(array $array): DateTime public setDate(int $year, int $month, int $day): DateTime public setISODate(int $year, int $week, int $day = 1): DateTime public setTime(int $hour, int $minute, int $second = 0): DateTime public setTimestamp(int $unixtimestamp): DateTime public setTimezone(DateTimeZone $timezone): DateTime public sub(DateInterval $interval): DateTime public diff(DateTimeInterface $datetime2, bool $absolute = false): DateInterval public format(string $format): string public getOffset(): int public getTimestamp(): int public getTimezone(): DateTimeZone public __wakeup() }
Constants
Let’s first take a look at the constants that we have.
constant name | value | example date |
---|---|---|
DateTimeInterface::ATOM | "Y-m-d\TH:i:sP" |
2022-08-09T22:46:19+02:00 |
DateTimeInterface::COOKIE | "l, d-M-Y H:i:s T" |
Tuesday, 09-Aug-2022 22:46:19 CEST |
DateTimeInterface::ISO8601 | "Y-m-d\TH:i:sO" |
2022-08-09T22:46:19+0200 |
DateTimeInterface::RFC822 | "D, d M y H:i:s O" |
Tue, 09 Aug 22 22:46:19 +0200 |
DateTimeInterface::RFC850 | "l, d-M-y H:i:s T" |
Tuesday, 09-Aug-22 22:46:19 CEST |
DateTimeInterface::RFC1036 | "D, d M y H:i:s O" |
Tue, 09 Aug 22 22:46:19 +0200 |
DateTimeInterface::RFC1123 | "D, d M Y H:i:s O" |
Tue, 09 Aug 2022 22:46:19 +0200 |
DateTimeInterface::RFC2822 | "D, d M Y H:i:s O" |
Tue, 09 Aug 2022 22:46:19 +0200 |
DateTimeInterface::RFC3339 | "Y-m-d\TH:i:sP" |
2022-08-09T22:46:19+02:00 |
DateTimeInterface::RFC3339_EXTENDED | "Y-m-d\TH:i:s.vP" |
2022-08-09T22:46:19.854+02:00 |
DateTimeInterface::RSS | "D, d M Y H:i:s O" |
Tue, 09 Aug 2022 22:46:19 +0200 |
DateTimeInterface::W3C | "Y-m-d\TH:i:sP" |
2022-08-09T22:46:19+02:00 |
These previously mentioned constants will be constants that you can use in the format. Run the following example on your PC
Example<!DOCTYPE html> <html> <body> <?php $objDateTime = new DateTime('NOW'); ?> <h1>my date now <?php echo $objDateTime->format('d-m-Y H:i:s');?></h1> lets check diferent constants for this date <h2>DateTimeInterface::ATOM </h2> <?php echo $objDateTime->format(DateTimeInterface::ATOM);?> <h2>DateTimeInterface::COOKIE</h2> <?php echo $objDateTime->format(DateTimeInterface::COOKIE);?> <h2>DateTimeInterface::ISO8601</h2> <?php echo $objDateTime->format(DateTimeInterface::ISO8601);?> <h2>DateTimeInterface::RFC822</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC822);?> <h2>DateTimeInterface::RFC850</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC850);?> <h2>DateTimeInterface::RFC1036</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC1036);?> <h2>DateTimeInterface::RFC1123</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC1123);?> <h2>DateTimeInterface::RFC2822</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC2822);?> <h2>DateTimeInterface::RFC3339</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC3339);?> <h2>DateTimeInterface::RFC3339_EXTENDED</h2> <?php echo $objDateTime->format(DateTimeInterface::RFC3339_EXTENDED);?> <h2>DateTimeInterface::RSS</h2> <?php echo $objDateTime->format(DateTimeInterface::RSS);?> <h2>DateTimeInterface::W3C</h2> <?php echo $objDateTime->format(DateTimeInterface::W3C);?> <!------> </body> </html>
Methods
We will see all the methods that we can use with the DateTime
class, most of them returning DateTime
, and also other classes that we will see later in this blog.
__construct()
https://blastcoding.com/en/php-datetime-class/#__constructIt returns a new DateTime
object, with 2 arguments: $time
with a default value of 'now'
and $timezone
with a default value of null
.
__construct(string $time = "now", DateTimeZone $timezone = null)
This means that in many cases, it’s not necessary to pass these arguments to the constructor.
constructor sin argumentos//blastcoding.com example //take in consideration that we are using now so your date will be your actual date <?php try { $fecha = new DateTime(); } catch (Exception $e) { echo $e->getMessage(); exit(1); } echo $fecha->format('Y-m-d');
2022-08-09
Let’s see some more examples to make things clearer.
<?php // Fecha/hora actuales en la zona horaria Uruguay. $fecha = new DateTime(null, new DateTimeZone('America/Montevideo')); echo $fecha->format('Y-m-d H:i:sP') . "\n"; // Fecha/hora actuales en la zona horaria España. $fecha = new DateTime(null, new DateTimeZone('Europe/Madrid')); echo $fecha->format('Y-m-d H:i:sP') . "\n";
2022-08-09 20:54:13-03:00 2022-08-10 01:54:13+02:00
add
https://blastcoding.com/en/php-datetime-class/#addWith this add method, we can modify a DateTime
object by adding years, months, days, hours, minutes, and seconds
$obj
in the following syntax must be a DateTime
object
$obj->add(DateInterval $interval): DateTime
In the following example, we will see how to use add by adding one year or subtracting one year
<?php $fecha = new DateTime(); echo $fecha->format('Y-m-d H:i:sP'); $fecha2=clone $fecha; $fecha3=clone $fecha; $fecha2->add(DateInterval::createFromDateString('1 year')); echo "\n".$fecha2->format('Y-m-d H:i:sP'); $fecha3->add(DateInterval::createFromDateString('-1 year')); echo "\n".$fecha3->format('Y-m-d H:i:sP');
DateTime::createFromFormat
https://blastcoding.com/en/php-datetime-class/#createFromFormatParses a time string according to a specified format
php.net
On my part, I would translate it as: This method creates or converts a string that represents a date into a DateTime
public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false
As we can see, DateTime::createFromFormat has 3 arguments, with one of them being optional. $format
is a string that represents the new format, $datetime
is the string to be parsed and converted to a DateTime
object. If it fails, it will return false
.
Let’s see some examples:
Ejemplo dado en php.net por falundir[at]gmail[dot]com<?php $date = DateTime::createFromFormat('Y-m-d', '2012-10-17'); var_dump($date->format('Y-m-d H:i:s')); //will print 2012-10-17 13:57:34 (the current time) ?>
You don’t have to be a genius to realize that this method can be quite helpful when retrieving data from a database and then converting it into a format that suits us.
DateTime::createFromImmutable
https://blastcoding.com/en/php-datetime-class/#createFromImmutableThis method creates a DateTime
object from a DateTimeImmutable
object, taking the data that the immutable object had. The immutable object is not changed in any way.
DateTime::createFromImmutable(DateTimeImmutable $object): DateTimecreateFromImmutable example
<?php $date = new DateTimeImmutable("2014-06-20 11:45 Europe/London"); $mutable = DateTime::createFromImmutable( $date ); ?>
DateTime::createFromInterface
https://blastcoding.com/en/php-datetime-class/#createFromInterfaceBoth DateTime
and DateTimeImmutable
use DateTimeInterface
, and it’s practical to be able to create a new DateTime
object from the object that uses this interface.
DateTime::createFromInterface(DateTimeInterface $object): DateTime
<?php $date = new DateTimeImmutable("2014-06-20 11:45 Europe/London"); $mutable = DateTime::createFromInterface($date); $date = new DateTime("2014-06-20 11:45 Europe/London"); $also_mutable = DateTime::createFromInterface($date); ?>
DateTime::getLastErrors
https://blastcoding.com/en/php-datetime-class/#getLastErrorsThis static method returns both the warnings and errors found in an array, and false if there are no errors or warnings
SintaxisDateTime::getLastErrors(): array|false
modify
https://blastcoding.com/en/php-datetime-class/#modifyThis method modifies the timestamp of a DateTime
object. It returns false
if it fails.
In the following code, $obj
represents a DateTime
object.
$obj->modify(string $modifier): DateTime|falsemodify example
<?php $date = new DateTime('2006-12-12'); $date->modify('+1 month'); echo $date->format('Y-m-d'); ?>
__set_state
https://blastcoding.com/en/php-datetime-class/#__set_stateThis method runs when var_export()
is called on our DateTime
object. Keep in mind that var_export()
is similar to var_dump()
, except that the returned code is executable
DateTime::__set_state(array $array): DateTime
Let’s see an example of this
Using var_export()<?php $date = DateTime::createFromFormat('Y-m-d', '2012-10-17'); var_export($date);
DateTime::__set_state(array( 'date' => '2012-10-17 15:28:13.000000', 'timezone_type' => 3, 'timezone' => 'UTC', ))
The code we had obtained in the example is completely executable
setDate
https://blastcoding.com/en/php-datetime-class/#setDateMethod to define/set a date.
Sintaxis$obj->setDate(int $year, int $month, int $day): DateTime
This method will return a DateTime
object.
<?php $date = new DateTime(); echo "today date: ".$date->format('d-m-Y'); echo "\n new date setted:" ; $date->setDate(2002, 7, 30); echo $date->format('Y-m-d'); ?>
setISODate
https://blastcoding.com/en/php-datetime-class/#setISODateThis method sets the date based on the ISO 8601 standard using weeks and days instead of specific dates.
Sintaxis$obj->setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime
setTime
https://blastcoding.com/en/php-datetime-class/#setTimeSet the time.
$obj
in the following syntax represents a DateTime
object.
$obj->setTime( int $hour, int $minute, int $second = 0, int $microsecond = 0 ): DateTime
setTimestamp
https://blastcoding.com/en/php-datetime-class/#setTimestampSets the date and time based on a Unix timestamp.
Sintaxis$obj->setTimestamp(int $timestamp): DateTime
setTimezone
https://blastcoding.com/en/php-datetime-class/#setTimezoneSet a new Timezone for a DateTime
object.
$obj->setTimezone(DateTimeZone $timezone): DateTimeExample
$obj->setTimezone(new DateTimeZone('America/New_York'));
sub
https://blastcoding.com/en/php-datetime-class/#subThis method subtracts years, months, days, hours, and seconds from a DateTime
object.
$obj->sub(DateInterval $interval): DateTimesub method example
$fecha_hora = new DateTime('2023-04-23 12:00:00'); $intervalo = new DateInterval('PT2H'); // Restar 2 horas $fecha_hora->sub($intervalo); echo $fecha_hora->format('Y-m-d H:i:s'); // Imprime "2023-04-23 10:00:00"
2023-04-23 10:00:00
diff
https://blastcoding.com/en/php-datetime-class/#diffReturns the difference between 2 dates as a DateInterval
object, which can be formatted into a string using the format method for display purposes.
public diff(DateTimeInterface $datetime2, bool $absolute = false): DateInterval
As an example, we could do the following:
ejemplo de diff$fecha1 = new DateTime('2023-04-23 12:00:00'); $fecha2 = new DateTime('2023-04-23 10:00:00'); $diferencia = $fecha1->diff($fecha2); echo $diferencia->format('%H:%I:%S');
02:00:00
format
https://blastcoding.com/en/php-datetime-class/#formatWith this method we can format the date of a DateTime
, DateTimeImmutable
or any object that uses the DateTimeInterface
.
public format(string $format): string
Although we already have a bunch of examples on format constants, I’ll leave an example here:
Ejemplo de format$fecha_hora = new DateTime('2023-04-23 12:00:00'); $ff = $fecha_hora->format('d-m-Y H:i'); echo $ff;
getOffset
https://blastcoding.com/en/php-datetime-class/#getOffsetIt returns the time offset. In certain countries, there may be a time offset depending on whether it is winter or summer, for example in Uruguay and Argentina, the clock is usually moved forward by one hour.
The getOffset
method returns an integer which represents the offset in seconds from UTC.
public getOffset(): int
The following is an example given on the php.net page.
ejemplo de getOffset$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York')); $summer = new DateTimeImmutable('2008-06-21', new DateTimeZone('America/New_York')); $gw = new DateTimeImmutable('2008-06-21', new DateTimeZone('UTC')); echo $winter->getOffset() . "\n"; echo $summer->getOffset() . "\n"; echo $gw->getOffset()."\n";
-18000 -14400 0
Note that in the example, I added the GMT timezone so that you know what time zone it’s being compared to.
getTimestamp
https://blastcoding.com/en/php-datetime-class/#getTimestampObtains the UNIX Timestamp
Sinopsis / Synopsispublic getTimestamp(): intEjemplo getTimestamp
$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York')); echo $winter->getTimestamp();
1292907600
getTimezone
https://blastcoding.com/en/php-datetime-class/#getTimezoneThis function returns the time zone relative to the given DateTime
as a DateTimeZone
object and false
if it fails to return the object.
public getTimezone(): DateTimeZone
$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York')); var_dump($winter->getTimezone());
object(DateTimeZone)#2 (2) { ["timezone_type"]=> int(3) ["timezone"]=> string(16) "America/New_York" }
__wakeup()
Sinopsis / Synopsispublic __wakeup()