Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP DateTime Class

Unlike date, DateTime is a class for representing both the date and the time.

Sinopsis / Synopsis
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()


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

<!DOCTYPE html>
        $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);?>
        <?php echo $objDateTime->format(DateTimeInterface::COOKIE);?>
        <?php echo $objDateTime->format(DateTimeInterface::ISO8601);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC822);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC850);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC1036);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC1123);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC2822);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC3339);?>
        <?php echo $objDateTime->format(DateTimeInterface::RFC3339_EXTENDED);?>
        <?php echo $objDateTime->format(DateTimeInterface::RSS);?>
        <?php echo $objDateTime->format(DateTimeInterface::W3C);?>


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.


It 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
// example
//take in consideration that we are using now so your date will be your actual date 
try {
   $fecha = new DateTime();
} catch (Exception $e) {
    echo $e->getMessage();
echo $fecha->format('Y-m-d');

Let’s see some more examples to make things clearer.


// 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


With 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

$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');


Parses a time string according to a specified format

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.

If the time portion is not given in $datetime, when the object is created, it will not be 00:00:00 but the time when the method was called.

Let’s see some examples:

Ejemplo dado en por falundir[at]gmail[dot]com
$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.


This 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): DateTime
createFromImmutable example
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");

$mutable = DateTime::createFromImmutable( $date );


Both 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
$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);


This static method returns both the warnings and errors found in an array, and false if there are no errors or warnings

DateTime::getLastErrors(): array|false


This 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|false
modify example
$date = new DateTime('2006-12-12');
$date->modify('+1 month');
echo $date->format('Y-m-d');


This 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()
$date = DateTime::createFromFormat('Y-m-d', '2012-10-17');
   'date' => '2012-10-17 15:28:13.000000',
   'timezone_type' => 3,
   'timezone' => 'UTC',

The code we had obtained in the example is completely executable


Method to define/set a date.

$obj->setDate(int $year, int $month, int $day): DateTime

This method will return a DateTime object.

setDate example
$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');


This method sets the date based on the ISO 8601 standard using weeks and days instead of specific dates.

$obj->setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime


Set the time.

$obj in the following syntax represents a DateTime object.

    int $hour,
    int $minute,
    int $second = 0,
    int $microsecond = 0
): DateTime


Sets the date and time based on a Unix timestamp.

$obj->setTimestamp(int $timestamp): DateTime


Set a new Timezone for a DateTime object.

$obj->setTimezone(DateTimeZone $timezone): DateTime
$obj->setTimezone(new DateTimeZone('America/New_York'));


This method subtracts years, months, days, hours, and seconds from a DateTime object.

$obj->sub(DateInterval $interval): DateTime
sub method example
$fecha_hora = new DateTime('2023-04-23 12:00:00');
$intervalo = new DateInterval('PT2H'); // Restar 2 horas

echo $fecha_hora->format('Y-m-d H:i:s'); // Imprime "2023-04-23 10:00:00"
2023-04-23 10:00:00


Returns the difference between 2 dates as a DateInterval object, which can be formatted into a string using the format method for display purposes.

Sinopsis / Synopsis
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');


With this method we can format the date of a DateTime, DateTimeImmutable or any object that uses the DateTimeInterface.

Sinopsis / Synopsis
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;


It 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.

Sinopsis / Synopsis
public getOffset(): int

The following is an example given on the 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";

Note that in the example, I added the GMT timezone so that you know what time zone it’s being compared to.


Obtains the UNIX Timestamp

Sinopsis / Synopsis
public getTimestamp(): int
Ejemplo getTimestamp
$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York'));
echo $winter->getTimestamp();


This function returns the time zone relative to the given DateTime as a DateTimeZone object and false if it fails to return the object.

Sinopsis / Synopsis
public getTimezone(): DateTimeZone
$winter = new DateTimeImmutable('2010-12-21', new DateTimeZone('America/New_York'));
object(DateTimeZone)#2 (2) {
  string(16) "America/New_York"


Sinopsis / Synopsis
public __wakeup()
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category