PHP DateTime Class Methods

Author — Nitish Kumar

On This Page
  1. PHP DateTime::add() Method
    1. What does DateTime::add() do?
    2. PHP DateTime::add() Syntax
    3. PHP DateTime::add() Parameters
    4. PHP DateTime::add() Return Value
    5. PHP DateTime::add() Working Examples
      1. 1. DateTime::add() example
      2. 2. Further DateTime::add() examples
      3. 3. Beware when adding months
    6. Additional Tips from Fellow Developers
  2. PHP DateTime::__construct() Method
    1. What does DateTime::__construct() do?
    2. PHP DateTime::__construct() Syntax
    3. PHP DateTime::__construct() Parameters
    4. PHP DateTime::__construct() Return Value
    5. PHP DateTime::__construct() Working Examples
      1. 1. DateTime::__construct() example
      2. 2. Intricacies of DateTime::__construct()
    6. Changelog for PHP DateTime::__construct() Method
    7. Important Points about PHP DateTime::__construct() Method
    8. Additional Tips from Fellow Developers
  3. PHP DateTime::createFromFormat() Method
    1. What does DateTime::createFromFormat() do?
    2. PHP DateTime::createFromFormat() Syntax
    3. PHP DateTime::createFromFormat() Parameters
    4. PHP DateTime::createFromFormat() Return Value
    5. PHP DateTime::createFromFormat() Working Examples
      1. 1. DateTime::createFromFormat() example
      2. 2. Intricacies of DateTime::createFromFormat()
      3. 3. Format string with literal characters
    6. Changelog for PHP DateTime::createFromFormat() Method
    7. Important Points about PHP DateTime::createFromFormat() Method
    8. Additional Tips from Fellow Developers
  4. PHP DateTime::createFromImmutable() Method
    1. What does DateTime::createFromImmutable() do?
    2. PHP DateTime::createFromImmutable() Syntax
    3. PHP DateTime::createFromImmutable() Parameters
    4. PHP DateTime::createFromImmutable() Return Value
    5. PHP DateTime::createFromImmutable() Working Examples
      1. 1. Creating a mutable date time object
  5. PHP DateTime::getLastErrors() Method
    1. What does DateTime::getLastErrors() do?
    2. PHP DateTime::getLastErrors() Syntax
    3. PHP DateTime::getLastErrors() Parameters
    4. PHP DateTime::getLastErrors() Return Value
    5. PHP DateTime::getLastErrors() Working Examples
      1. 1. DateTime::getLastErrors() example
  6. PHP DateTime::modify() Method
    1. What does DateTime::modify() do?
    2. PHP DateTime::modify() Syntax
    3. PHP DateTime::modify() Parameters
    4. PHP DateTime::modify() Return Value
    5. PHP DateTime::modify() Working Examples
      1. 1. DateTime::modify() example
      2. 2. Beware when adding or subtracting months
    6. Changelog for PHP DateTime::modify() Method
    7. Additional Tips from Fellow Developers
  7. PHP DateTime::setDate() Method
    1. What does DateTime::setDate() do?
    2. PHP DateTime::setDate() Syntax
    3. PHP DateTime::setDate() Parameters
    4. PHP DateTime::setDate() Return Value
    5. PHP DateTime::setDate() Working Examples
      1. 1. DateTime::setDate() example
      2. 2. Values exceeding ranges are added to their parent values
    6. Changelog for PHP DateTime::setDate() Method
  8. PHP DateTime::setISODate() Method
    1. What does DateTime::setISODate() do?
    2. PHP DateTime::setISODate() Syntax
    3. PHP DateTime::setISODate() Parameters
    4. PHP DateTime::setISODate() Return Value
    5. PHP DateTime::setISODate() Working Examples
      1. 1. DateTime::setISODate() example
      2. 2. Values exceeding ranges are added to their parent values
      3. 3. Finding the month a week is in
    6. Changelog for PHP DateTime::setISODate() Method
  9. PHP DateTime::setTime() Method
    1. What does DateTime::setTime() do?
    2. PHP DateTime::setTime() Syntax
    3. PHP DateTime::setTime() Parameters
    4. PHP DateTime::setTime() Return Value
    5. PHP DateTime::setTime() Working Examples
      1. 1. DateTime::setTime() example
      2. 2. Values exceeding ranges are added to their parent values
    6. Changelog for PHP DateTime::setTime() Method
  10. PHP DateTime::setTimestamp() Method
    1. What does DateTime::setTimestamp() do?
    2. PHP DateTime::setTimestamp() Syntax
    3. PHP DateTime::setTimestamp() Parameters
    4. PHP DateTime::setTimestamp() Return Value
    5. PHP DateTime::setTimestamp() Working Examples
      1. 1. DateTime::setTimestamp() example
      2. 2. DateTime::setTimestamp() alternative in PHP 5.2
    6. Additional Tips from Fellow Developers
  11. PHP DateTime::setTimezone() Method
    1. What does DateTime::setTimezone() do?
    2. PHP DateTime::setTimezone() Syntax
    3. PHP DateTime::setTimezone() Parameters
    4. PHP DateTime::setTimezone() Return Value
    5. PHP DateTime::setTimezone() Working Examples
      1. 1. DateTime::setTimeZone() example
    6. Changelog for PHP DateTime::setTimezone() Method
    7. Additional Tips from Fellow Developers
  12. PHP DateTime::__set_state() Method
    1. What does DateTime::__set_state() do?
    2. PHP DateTime::__set_state() Syntax
    3. PHP DateTime::__set_state() Parameters
    4. PHP DateTime::__set_state() Return Value
  13. PHP DateTime::sub() Method
    1. What does DateTime::sub() do?
    2. PHP DateTime::sub() Syntax
    3. PHP DateTime::sub() Parameters
    4. PHP DateTime::sub() Return Value
    5. PHP DateTime::sub() Working Examples
      1. 1. DateTime::sub() example
      2. 2. Further DateTime::sub() examples
      3. 3. Beware when subtracting months
    6. Additional Tips from Fellow Developers

PHP DateTime::add() Method

What does DateTime::add() do?

The PHP DateTime::add() method adds an amount of days, months, years, hours, minutes and seconds to a DateTime object .

PHP DateTime::add() Syntax

 public DateTime::add ( DateInterval $interval ) : DateTime
 date_add ( DateTime $object , DateInterval $interval ) : DateTime

PHP DateTime::add() Parameters

  1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

  2. interval — A DateInterval object

PHP DateTime::add() Return Value

The PHP DateTime::add() method returns the DateTime object for method chaining or FALSE on failure.

PHP DateTime::add() Working Examples

1. DateTime::add() example

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P10D'));
echo $date->format('Y-m-d') . "\n";
?>

Output of the above code:

2000-01-11

2. Further DateTime::add() examples

<?php
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s') . "\n";
$date = new DateTime('2000-01-01');
$date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $date->format('Y-m-d H:i:s') . "\n";
?>

Output of the above code:

2000-01-01 10:00:30
2007-06-05 04:03:02

3. Beware when adding months

<?php
$date = new DateTime('2000-12-31');
$interval = new DateInterval('P1M');
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
$date->add($interval);
echo $date->format('Y-m-d') . "\n";
?>

Output of the above code:

2001-01-31
2001-03-03

Additional Tips from Fellow Developers

Contributed By: Anonymous

Note that the add() and sub() methods will modify the value of the object you're calling the method on! This is very untypical for a method that returns a value of its own type. You could misunderstand it that the method would return a new instance with the modified value, but in fact it modifies itself! This is undocumented here. (Only a side note on procedural style mentions it, but it obviously does not apply to object oriented style.)

Contributed By: Angelo

Another simple solution to adding a month but not autocorrecting days to the next month is this.
(Also works for substracting months)
$dt = new DateTime("2016-01-31");
$oldDay = $dt->format("d");
$dt->add(new DateInterval("P1M")); // 2016-03-02
$newDay = $dt->format("d");
if($oldDay != $newDay) {
    // Check if the day is changed, if so we skipped to the next month.
    // Substract days to go back to the last day of previous month.
    $dt->sub(new DateInterval("P" . $newDay . "D"));
}
echo $dt->format("Y-m-d"); // 2016-02-29
Hope this helps someone.

Contributed By: Anthony

If you're using PHP >= 5.5, instead of using "glavic at gmail dot com"'s DateTimeEnhanced class, use the built in DateTimeImmutable type. When you call DateTimeImmutable::add() it will return a new object, rather than modifying the original

Contributed By: patrick dot mckay7

Here is a solution to adding months when you want 2014-10-31 to become 2014-11-30 instead of 2014-12-01.
<?php
/**
 * Class MyDateTime
 *
 * Extends DateTime to include a sensible addMonth method.
 *
 * This class provides a method that will increment the month, and
 * if the day is greater than the last day in the new month, it
 * changes the day to the last day of that month. For example,
 * If you add one month to 2014-10-31 using DateTime::add, the
 * result is 2014-12-01. Using MyDateTime::addMonth the result is
 * 2014-11-30.
 */
class MyDateTime extends DateTime
{
    public function addMonth($num = 1)
    {
        $date = $this->format('Y-n-j');
        list($y, $m, $d) = explode('-', $date);
        $m += $num;
        while ($m > 12)
        {
            $m -= 12;
            $y++;
        }
        $last_day = date('t', strtotime("$y-$m-1"));
        if ($d > $last_day)
        {
            $d = $last_day;
        }
        $this->setDate($y, $m, $d);
    }
}
?>

Contributed By: glavic

If you need add() and sub() that don't modify object values, you can create new methods like this:
<?php
class DateTimeEnhanced extends DateTime {
    public function returnAdd(DateInterval $interval)
    {
        $dt = clone $this;
        $dt->add($interval);
        return $dt;
    }
    
    public function returnSub(DateInterval $interval)
    {
        $dt = clone $this;
        $dt->sub($interval);
        return $dt;
    }
}
$interval = DateInterval::createfromdatestring('+1 day');
$dt = new DateTimeEnhanced; # initialize new object
echo $dt->format(DateTime::W3C) . "\n"; # 2013-09-12T15:01:44+02:00
$dt->add($interval); # this modifies the object values
echo $dt->format(DateTime::W3C) . "\n"; # 2013-09-13T15:01:44+02:00
$dtNew = $dt->returnAdd($interval); # this returns the new modified object and doesn't change original object
echo $dt->format(DateTime::W3C) . "\n"; # 2013-09-13T15:01:44+02:00
echo $dtNew->format(DateTime::W3C) . "\n"; # 2013-09-14T15:01:44+02:00

PHP DateTime::__construct() Method

What does DateTime::__construct() do?

The PHP DateTime::__construct() method will give you new DateTime object.

PHP DateTime::__construct() Syntax

 date_create ([ string $datetime = "now" [, DateTimeZone $timezone = NULL ]] ) : DateTime

PHP DateTime::__construct() Parameters

  1. datetime — A date/time string. Valid formats are explained in Date and Time Formats.

  2. timezone — A DateTimeZone object representing the timezone of $datetime.

PHP DateTime::__construct() Return Value

The PHP DateTime::__construct() method returns a new DateTime instance. Procedural style return FALSE on failure.

PHP DateTime::__construct() Working Examples

1. DateTime::__construct() example

<?php
try {
    $date = new DateTime('2000-01-01');
} catch (Exception $e) {
    echo $e->getMessage();
    exit(1);
}
echo $date->format('Y-m-d');
?>

Output of the above code:

2000-01-01

2. Intricacies of DateTime::__construct()

<?php
// Specified date/time in your computer's time zone.
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Specified date/time in the specified time zone.
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in your computer's time zone.
$date = new DateTime();
echo $date->format('Y-m-d H:i:sP') . "\n";
// Current date/time in the specified time zone.
$date = new DateTime(null, new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
// Using a UNIX timestamp.  Notice the result is in the UTC time zone.
$date = new DateTime('@946684800');
echo $date->format('Y-m-d H:i:sP') . "\n";
// Non-existent values roll over.
$date = new DateTime('2000-02-30');
echo $date->format('Y-m-d H:i:sP') . "\n";
?>

Output of the above code:

2000-01-01 00:00:00-05:00
2000-01-01 00:00:00+12:00
2010-04-24 10:24:16-04:00
2010-04-25 02:24:16+12:00
2000-01-01 00:00:00+00:00
2000-03-01 00:00:00-05:00

Changelog for PHP DateTime::__construct() Method

7.1 — From now on microseconds are filled with actual value. Not with ‘00000’.

5.3.0 — If datetime contains an invalid date/time format, then an exception is now thrown. Previously an error was emitted.

Important Points about PHP DateTime::__construct() Method

  1. 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).

Additional Tips from Fellow Developers

Contributed By: cHao

There's a reason for ignoring the time zone when you pass a timestamp to __construct.  That is, UNIX timestamps are by definition based on UTC.  @1234567890 represents the same date/time regardless of time zone.  So there's no need for a time zone at all.

Contributed By: kendsnyder

The theoretical limits of the date range seem to be "-9999-01-01" through "9999-12-31" (PHP 5.2.9 on Windows Vista 64):
<?php
$d = new DateTime("9999-12-31"); 
$d->format("Y-m-d"); // "9999-12-31"
$d = new DateTime("0000-12-31"); 
$d->format("Y-m-d"); // "0000-12-31"
$d = new DateTime("-9999-12-31"); 
$d->format("Y-m-d"); // "-9999-12-31"
?>
Dates above 10000 and below -10000 do not throw errors but produce weird results:
<?php
$d = new DateTime("10019-01-01"); 
$d->format("Y-m-d"); // "2009-01-01"
$d = new DateTime("10009-01-01"); 
$d->format("Y-m-d"); // "2009-01-01"
$d = new DateTime("-10019-01-01"); 
$d->format("Y-m-d"); // "2009-01-01"
?>

Contributed By: joel dot kallman

A definite "gotcha" (while documented) that exists in the __construct is that it ignores your timezone if the $time is a timestamp.  While this may not make sense, the object does provide you with methods to work around it. 
 
<?php 
// New Timezone Object 
$timezone = new DateTimeZone('America/New_York'); 
 
// New DateTime Object 
$date =  new DateTime('@1306123200', $timezone);    
 
// You would expect the date to be 2011-05-23 00:00:00 
// But it actually outputs 2011-05-23 04:00:00 
echo $date->format('Y-m-d H:i:s'); 
 
// You can still set the timezone though like so...        
$date->setTimezone($timezone); 
 
// This will now output 2011-05-23 00:00:00 
echo $date->format('Y-m-d H:i:s'); 
?>

PHP DateTime::createFromFormat() Method

What does DateTime::createFromFormat() do?

The PHP DateTime::createFromFormat() method parses a time string according to a specified format.

PHP DateTime::createFromFormat() Syntax

 public static DateTime::createFromFormat ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTime
 date_create_from_format ( string $format , string $datetime [, DateTimeZone $timezone ] ) : DateTime

PHP DateTime::createFromFormat() Parameters

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

  2. datetime — String representing the time.

  3. timezone — A DateTimeZone object representing the desired time zone.

PHP DateTime::createFromFormat() Return Value

The PHP DateTime::createFromFormat() method returns a new DateTime instance or FALSE on failure.

PHP DateTime::createFromFormat() Working Examples

1. DateTime::createFromFormat() example

<?php
$date = DateTime::createFromFormat('j-M-Y', '15-Feb-2009');
echo $date->format('Y-m-d');
?>

Output of the above code:

2009-02-15

2. Intricacies of DateTime::createFromFormat()

<?php
echo 'Current time: ' . date('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d';
$date = DateTime::createFromFormat($format, '2009-02-15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = 'Y-m-!d H:i:s';
$date = DateTime::createFromFormat($format, '2009-02-15 15:16:17');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
$format = '!d';
$date = DateTime::createFromFormat($format, '15');
echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n";
?>

Output of the above code:

Current time: 2010-04-23 10:29:35
Format: Y-m-d; 2009-02-15 10:29:35
Format: Y-m-d H:i:s; 2009-02-15 15:16:17
Format: Y-m-!d H:i:s; 1970-01-15 15:16:17
Format: !d; 1970-01-15 00:00:00

3. Format string with literal characters

<?php
echo DateTime::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s');
?>

Output of the above code:

23:15:03

Changelog for PHP DateTime::createFromFormat() Method

7.3.0 — The v format specifier has been added.

5.3.9 — The + format specifier has been added.

Important Points about PHP DateTime::createFromFormat() Method

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

Additional Tips from Fellow Developers

Contributed By: falundir

Be warned that DateTime object created without explicitely providing the time portion will have the current time set instead of 00:00:00.
<?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)
?>
That's also why you can't safely compare equality of such DateTime objects:
<?php
$date1 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date1 == $date2); //will be false
var_dump($date1 >= $date2); //will be false
var_dump($date1 < $date2); //will be true
?>

Contributed By: Albie

If you want to safely compare equality of a DateTime object without explicitly providing the time portion make use of the ! format character.
<?php
$date1 = DateTime::createFromFormat('!Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('!Y-m-d', '2012-10-17');
/* 
 $date1 and $date2 will both be set to a timestamp of "2012-10-17 00:00:00"
 var_dump($date1 == $date2); //will be true
 var_dump($date1 > $date2); //will be false
 var_dump($date1 < $date2); //will be false
*/
?>
If you omit the ! format character without explicitly providing the time portion your timestamp which will include the current system time in the stamp.
<?php
$date1 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
sleep(2);
$date2 = DateTime::createFromFormat('Y-m-d', '2012-10-17');
var_dump($date1 == $date2); //will be false
var_dump($date1 >= $date2); //will be false
var_dump($date1 < $date2); //will be true
?>

Contributed By: Fabian

Parsing RFC3339 strings can be very tricky when their are microseconds in the date string.
Since PHP 7 there is the undocumented constant DateTime::RFC3339_EXTENDED (value: Y-m-d\TH:i:s.vP), which can be used to output an RFC3339 string with microseconds:
<?php
$d = new DateTime();
var_dump($d->format(DateTime::RFC3339_EXTENDED)); // 2017-07-25T13:47:12.000+00:00
?>
But the same constant can't be used for parsing an RFC3339 string with microseconds, instead do:
<?php
$date = DateTime::createFromFormat("Y-m-d\TH:i:s.uP", "2017-07-25T15:25:16.123456+02:00")
?>
But "u" can only parse microseconds up to 6 digits, but some language (like Go) return more than 6 digits for the microseconds, e.g.: "2017-07-25T15:50:42.456430712+02:00" (when turning time.Time to JSON with json.Marshal()). Currently there is no other solution than using a separate parsing library to get correct dates.
Note: the difference between "v" and "u" is just 3 digits vs. 6 digits.

Contributed By: thflori

CreateFromFormat('U') has a strange behaviour: it ignores the datetimezone and the resulting DateTime object will always have GMT+0000 timezone.
<?php
$dt = DateTime::createFromFormat('U', time(), new DateTimeZone('CET'));
var_dump($dt->format('Y-m-d H:i:s (T)'), date('Y-m-d H:i:s (T)', time()));
?>
The problem is microtime() and time() returning the timestamp in current timezone.  Instead of using time you can use 'now' but to get a DateTimeObject with microseconds you have to write it this way to be sure to get the correct datetime:
<?php
$dt = \DateTime::createFromFormat('U.u', microtime(true))->setTimezone(new \DateTimeZone(date('T')));
?>

Contributed By: d dot shankarnarayana

Say if there is a string with  $date = "today is 2014 January 1";   and you need to extract "2014 January" using DateTime::createFromFormat().  As you can see in the string there is something odd like "today is" .Since that string (today is) does not correspond to a date format, we need to escape that. 
In this case, each and every character on that string has to be escaped as shown below.
The code.
<?php
$paragraph = "today is 2014 January 1";
$date = DateTime::createFromFormat('\t\o\d\a\y \i\s Y F j', $paragraph);
echo $date->format('Y F'); //"prints" 2014 January
- Shankar Damodaran

Contributed By: lsloan-php dot net

Reportedly, microtime() may return a timestamp number without a fractional part if the microseconds are exactly zero.  I.e., "1463772747" instead of the expected "1463772747.000000".  number_format() can create a correct string representation of the microsecond timestamp every time, which can be useful for creating DateTime objects when used with DateTime::createFromFormat():
<?php
$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
var_dump($now->format('Y-m-d H:i:s.u')); // E.g., string(26) "2016-05-20 19:36:26.900794"

Contributed By: tuxedobob

If you're here because you're trying to create a date from a week number, you want to be using setISODate, as I discovered here:
http://www.lornajane.net/posts/2011/getting-dates-from-week-numbers-in-php

Contributed By: ELPI

It can be confusing creating new DateTime from timestamp when your default timezone (date.timezone) is different from UTC and you are used to date()-function.
date()-function automatically uses your current timezone setting but DateTime::createFromFormat (or DateTime constructor) does not (it ignores tz-parameter).
You can get same results as date() by setting the timezone after object creation.
<?php
$ts = 1414706400;
$date1 = date("Y-m-d H:i", $ts);
$date2 = DateTime::createFromFormat("U", $ts)->setTimeZone(new DateTimeZone(date_default_timezone_get()))->format("Y-m-d H:i");
//$date1===$date2
?>

Contributed By: nicodoggie

I've found that on PHP 5.5.13 (not sure if it happens on other versions) if you enter a month larger than 12 on a format that takes numeric months, the result will be a DateTime object with its month equal to the number modulo 12 instead of returning false.
<?php
var_dump(DateTime::createFromFormat('Y-m-d', '2013-22-01'));
?>
results in:
class DateTime#4 (3) {
  public $date =>
  string(19) "2014-10-01 13:05:05"
  public $timezone_type =>
  int(3)
  public $timezone =>
  string(3) "UTC"
}

Contributed By: thomas dot ribiere

Not a bug, but a strange issue today 2012-08-30 :
<?php
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m",$date);
echo $d->format("Y-m");
?>
will display : 
2011-02
2011-03
It's because there is no 2011-02-30, so datetime will take march insteed of february ...
To fix it :
<?php 
$date = "2011-02";
echo $date."\n";
$d = DateTime::createFromFormat("Y-m-d",$date."-01");
echo $d->format("Y-m");
?>

PHP DateTime::createFromImmutable() Method

What does DateTime::createFromImmutable() do?

The PHP DateTime::createFromImmutable() method will give you new DateTime object encapsulating the given DateTimeImmutable object.

PHP DateTime::createFromImmutable() Syntax

 public static DateTime::createFromImmutable ( DateTimeImmutable $object ) : DateTime

PHP DateTime::createFromImmutable() Parameters

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

PHP DateTime::createFromImmutable() Return Value

The PHP DateTime::createFromImmutable() method returns a new DateTime instance.

PHP DateTime::createFromImmutable() Working Examples

1. Creating a mutable date time object

<?php
$date = new DateTimeImmutable("2014-06-20 11:45 Europe/London");
$mutable = DateTime::createFromImmutable( $date );
?>

PHP DateTime::getLastErrors() Method

What does DateTime::getLastErrors() do?

The PHP DateTime::getLastErrors() method will give you the warnings and errors.

PHP DateTime::getLastErrors() Syntax

 public static DateTime::getLastErrors ( void ) : array
 date_get_last_errors ( void ) : array

PHP DateTime::getLastErrors() Parameters

    This method does not accept any parameters.

    PHP DateTime::getLastErrors() Return Value

    The PHP DateTime::getLastErrors() method returns array containing info about warnings and errors.

    PHP DateTime::getLastErrors() Working Examples

    1. DateTime::getLastErrors() example

    <?php
    try {
        $date = new DateTime('asdfasdf');
    } catch (Exception $e) {
        // For demonstration purposes only...
        print_r(DateTime::getLastErrors());
        // The real object oriented way to do this is
        // echo $e->getMessage();
    }
    ?>

    Output of the above code:

    Array
    (
     [warning_count] => 1
     [warnings] => Array
     (
     [6] => Double timezone specification
     )
     [error_count] => 1
     [errors] => Array
     (
     [0] => The timezone could not be found in the database
     )
    )

    PHP DateTime::modify() Method

    What does DateTime::modify() do?

    The PHP DateTime::modify() method alters the timestamp.

    PHP DateTime::modify() Syntax

     public DateTime::modify ( string $modifier ) : DateTime
     date_modify ( DateTime $object , string $modifier ) : DateTime

    PHP DateTime::modify() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. modifier — A date/time string. Valid formats are explained in Date and Time Formats.

    PHP DateTime::modify() Return Value

    The PHP DateTime::modify() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::modify() Working Examples

    1. DateTime::modify() example

    <?php
    $date = new DateTime('2006-12-12');
    $date->modify('+1 day');
    echo $date->format('Y-m-d');
    ?>

    Output of the above code:

    2006-12-13

    2. Beware when adding or subtracting months

    <?php
    $date = new DateTime('2000-12-31');
    $date->modify('+1 month');
    echo $date->format('Y-m-d') . "\n";
    $date->modify('+1 month');
    echo $date->format('Y-m-d') . "\n";
    ?>

    Output of the above code:

    2001-01-31
    2001-03-03

    Changelog for PHP DateTime::modify() Method

    5.3.6 — Absolute date/time statements now take effect. Previously, only relative parts were used.

    5.3.0 — Changed the return value on success from NULL to DateTime.

    Additional Tips from Fellow Developers

    Contributed By: mangotonk

    A slightly more compact way of getting the month shift
    <?php
          /**
         * correctly calculates end of months when we shift to a shorter or longer month
         * workaround for http://php.net/manual/en/datetime.add.php#example-2489 
         * 
         * Makes the assumption that shifting from the 28th Feb +1 month is 31st March
         * Makes the assumption that shifting from the 28th Feb -1 month is 31st Jan
         * Makes the assumption that shifting from the 29,30,31 Jan +1 month is 28th (or 29th) Feb
         *
         * 
         * @param DateTime $aDate
         * @param int $months positive or negative
         * 
         * @return DateTime new instance - original parameter is unchanged
         */
        function MonthShifter (DateTime $aDate,$months){
            $dateA = clone($aDate);
            $dateB = clone($aDate);
            $plusMonths = clone($dateA->modify($months . ' Month'));
            //check whether reversing the month addition gives us the original day back
            if($dateB != $dateA->modify($months*-1 . ' Month')){ 
                $result = $plusMonths->modify('last day of last month');
            } elseif($aDate == $dateB->modify('last day of this month')){
                $result =  $plusMonths->modify('last day of this month');
            } else {
                $result = $plusMonths;
            }
            return $result;
        }
    //TEST
    $x = new DateTime('2017-01-30');
    echo( $x->format('Y-m-d')." past end of feb, but not dec<br>");
    echo('b ' . MonthShifter($x,1)->format(('Y-m-d'))."<br>");
    echo('c ' . MonthShifter($x,-1)->format(('Y-m-d'))."<br>");
    $x = new DateTime('2017-01-15');
    echo("<br>" . $x->format('Y-m-d')." middle of the month <br>");
    echo('d ' . MonthShifter($x,1)->format(('Y-m-d'))."<br>");
    echo('e ' . MonthShifter($x,-1)->format(('Y-m-d'))."<br>");
    $x = new DateTime('2017-02-28');
    echo("<br>" . $x->format('Y-m-d')." end of Feb<br>");
    echo('f ' . MonthShifter($x,1)->format(('Y-m-d'))."<br>");
    echo('g ' . MonthShifter($x,-1)->format(('Y-m-d'))."<br>");
    $x = new DateTime('2017-01-31');
    echo("<br>" .  $x->format('Y-m-d')." end of Jan<br>");
    echo('h ' . MonthShifter($x,1)->format(('Y-m-d'))."<br>");
    echo('i ' . MonthShifter($x,-1)->format(('Y-m-d'))."<br>");
    $x = new DateTime('2017-01-31');
    echo("<br>" .  $x->format('Y-m-d')." end of Jan +/- 1 years diff, leap year respected<br>");
    echo('j ' . MonthShifter($x,13)->format(('Y-m-d'))."<br>");
    echo('k ' . MonthShifter($x,-11)->format(('Y-m-d'))."<br>");
    //returns
    2017-01-30 past end of feb, but not dec
    b 2017-02-28
    c 2016-12-30
    2017-01-15 middle of the month 
    d 2017-02-15
    e 2016-12-15
    2017-02-28end of Feb
    f 2017-03-31
    g 2017-01-31
    2017-01-31end of Jan
    h 2017-02-28
    i 2016-12-31
    2017-01-31end of Jan +/- 1 years diff, leap year respected
    j 2018-02-28
    k 2016-02-29

    Contributed By: jenspj

    These functions makes sure that adding months or years always ends up in the month you would expect.  Works for positive and negative values
    <?php
          
           
        $date=new DateTime();
        $date->setDate(2008,2,29);
        
        function addMonths($date,$months){
             
            $init=clone $date;
            $modifier=$months.' months';
            $back_modifier =-$months.' months';
            
            $date->modify($modifier);
            $back_to_init= clone $date;
            $back_to_init->modify($back_modifier);
            
            while($init->format('m')!=$back_to_init->format('m')){
            $date->modify('-1 day')    ;
            $back_to_init= clone $date;
            $back_to_init->modify($back_modifier);    
            }
            
            /*
            if($months<0&&$date->format('m')>$init->format('m'))
            while($date->format('m')-12-$init->format('m')!=$months%12)
            $date->modify('-1 day');
            else
            if($months>0&&$date->format('m')<$init->format('m'))
            while($date->format('m')+12-$init->format('m')!=$months%12)
            $date->modify('-1 day');
            else
            while($date->format('m')-$init->format('m')!=$months%12)
            $date->modify('-1 day');
            */
            
        }
         
        function addYears($date,$years){
            
            $init=clone $date;
            $modifier=$years.' years';
            $date->modify($modifier);
            
            while($date->format('m')!=$init->format('m'))
            $date->modify('-1 day');
            
            
        } 
        
        
        
        addMonths($date,-1);
         addYears($date,3);
        
        
        echo $date->format('F j,Y');
         
     
    ?>

    PHP DateTime::setDate() Method

    What does DateTime::setDate() do?

    The PHP DateTime::setDate() method sets the date.

    PHP DateTime::setDate() Syntax

     public DateTime::setDate ( int $year , int $month , int $day ) : DateTime
     date_date_set ( DateTime $object , int $year , int $month , int $day ) : DateTime

    PHP DateTime::setDate() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. year — Year of the date.

    3. month — Month of the date.

    4. day — Day of the date.

    PHP DateTime::setDate() Return Value

    The PHP DateTime::setDate() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::setDate() Working Examples

    1. DateTime::setDate() example

    <?php
    $date = new DateTime();
    $date->setDate(2001, 2, 3);
    echo $date->format('Y-m-d');
    ?>

    Output of the above code:

    2001-02-03

    2. Values exceeding ranges are added to their parent values

    <?php
    $date = new DateTime();
    $date->setDate(2001, 2, 28);
    echo $date->format('Y-m-d') . "\n";
    $date->setDate(2001, 2, 29);
    echo $date->format('Y-m-d') . "\n";
    $date->setDate(2001, 14, 3);
    echo $date->format('Y-m-d') . "\n";
    ?>

    Output of the above code:

    2001-02-28
    2001-03-01
    2002-02-03

    Changelog for PHP DateTime::setDate() Method

    5.3.0 — Changed the return value on success from NULL to DateTime.

    PHP DateTime::setISODate() Method

    What does DateTime::setISODate() do?

    The PHP DateTime::setISODate() method sets the ISO date.

    PHP DateTime::setISODate() Syntax

     public DateTime::setISODate ( int $year , int $week [, int $dayOfWeek = 1 ] ) : DateTime
     date_isodate_set ( DateTime $object , int $year , int $week [, int $dayOfWeek = 1 ] ) : DateTime

    PHP DateTime::setISODate() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. year — Year of the date.

    3. week — Week of the date.

    4. dayOfWeek — Offset from the first day of the week.

    PHP DateTime::setISODate() Return Value

    The PHP DateTime::setISODate() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::setISODate() Working Examples

    1. DateTime::setISODate() example

    <?php
    $date = new DateTime();
    $date->setISODate(2008, 2);
    echo $date->format('Y-m-d') . "\n";
    $date->setISODate(2008, 2, 7);
    echo $date->format('Y-m-d') . "\n";
    ?>

    Output of the above code:

    2008-01-07
    2008-01-13

    2. Values exceeding ranges are added to their parent values

    <?php
    $date = new DateTime();
    $date->setISODate(2008, 2, 7);
    echo $date->format('Y-m-d') . "\n";
    $date->setISODate(2008, 2, 8);
    echo $date->format('Y-m-d') . "\n";
    $date->setISODate(2008, 53, 7);
    echo $date->format('Y-m-d') . "\n";
    ?>

    Output of the above code:

    2008-01-13
    2008-01-14
    2009-01-04

    3. Finding the month a week is in

    <?php
    $date = new DateTime();
    $date->setISODate(2008, 14);
    echo $date->format('n');
    ?>

    Output of the above code:

    3

    Changelog for PHP DateTime::setISODate() Method

    5.3.0 — Changed the return value on success from NULL to DateTime.

    PHP DateTime::setTime() Method

    What does DateTime::setTime() do?

    The PHP DateTime::setTime() method sets the time.

    PHP DateTime::setTime() Syntax

     public DateTime::setTime ( int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTime
     date_time_set ( DateTime $object , int $hour , int $minute [, int $second = 0 [, int $microsecond = 0 ]] ) : DateTime

    PHP DateTime::setTime() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. hour — Hour of the time.

    3. minute — Minute of the time.

    4. second — Second of the time.

    5. microsecond — Microsecond of the time.

    PHP DateTime::setTime() Return Value

    The PHP DateTime::setTime() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::setTime() Working Examples

    1. DateTime::setTime() example

    <?php
    $date = new DateTime('2001-01-01');
    $date->setTime(14, 55);
    echo $date->format('Y-m-d H:i:s') . "\n";
    $date->setTime(14, 55, 24);
    echo $date->format('Y-m-d H:i:s') . "\n";
    ?>

    Output of the above code:

    2001-01-01 14:55:00
    2001-01-01 14:55:24

    2. Values exceeding ranges are added to their parent values

    <?php
    $date = new DateTime('2001-01-01');
    $date->setTime(14, 55, 24);
    echo $date->format('Y-m-d H:i:s') . "\n";
    $date->setTime(14, 55, 65);
    echo $date->format('Y-m-d H:i:s') . "\n";
    $date->setTime(14, 65, 24);
    echo $date->format('Y-m-d H:i:s') . "\n";
    $date->setTime(25, 55, 24);
    echo $date->format('Y-m-d H:i:s') . "\n";
    ?>

    Output of the above code:

    2001-01-01 14:55:24
    2001-01-01 14:56:05
    2001-01-01 15:05:24
    2001-01-02 01:55:24

    Changelog for PHP DateTime::setTime() Method

    7.1.0 — The microsecond parameter was added.

    5.3.0 — Changed the return value on success from NULL to DateTime.

    PHP DateTime::setTimestamp() Method

    What does DateTime::setTimestamp() do?

    The PHP DateTime::setTimestamp() method sets the date and time based on an Unix timestamp.

    PHP DateTime::setTimestamp() Syntax

     public DateTime::setTimestamp ( int $timestamp ) : DateTime
     date_timestamp_set ( DateTime $object , int $timestamp ) : DateTime

    PHP DateTime::setTimestamp() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. timestamp — Unix timestamp representing the date.

    PHP DateTime::setTimestamp() Return Value

    The PHP DateTime::setTimestamp() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::setTimestamp() Working Examples

    1. DateTime::setTimestamp() example

    <?php
    $date = new DateTime();
    echo $date->format('U = Y-m-d H:i:s') . "\n";
    $date->setTimestamp(1171502725);
    echo $date->format('U = Y-m-d H:i:s') . "\n";
    ?>

    Output of the above code:

    1272508903 = 2010-04-28 22:41:43
    1171502725 = 2007-02-14 20:25:25

    2. DateTime::setTimestamp() alternative in PHP 5.2

    <?php
    $ts = 1171502725;
    $date = new DateTime("@$ts");
    echo $date->format('U = Y-m-d H:i:s') . "\n";
    ?>

    Output of the above code:

    1171502725 = 2007-02-14 20:25:25

    Additional Tips from Fellow Developers

    Contributed By: admin

    It should be noted above, be careful when manipulating the DateTime object with unix timestamps.
    In the above examples you will get varying results dependent on your current timezone, method used, and version of PHP.
    One would expect all of the examples above to perform the same as setTimestamp() or date('H:i', $timestamp); would.
    <?php
    date_default_timezone_set('America/New_York');
    $ts = 1171502725;
    ?>
    Set timestamp from UTC timezone use UTC timezone
    <?php
    $date = new DateTime("@$ts"); 
    var_dump($date->format('Y-m-d H:i:s e'));
    /*
    string(26) "2007-02-15 01:25:25 +00:00" //PHP 5.3.0 - 5.6.8
    */
    ?>
    To convert the above to use the current timezone simply use
    <?php
    $date->setTimezone(date_default_timezone_get());
    //string(36) "2007-02-14 20:25:25 America/New_York"
    ?>
    Set the timestamp from UTC timezone use current timezone
    <?php
    $date = new DateTime;
    $date->modify('@' . $ts); 
    var_dump($date->format('Y-m-d H:i:s e'));
    /*
    string(36) "2007-02-15 01:25:25 America/New_York" //PHP 5.3.6 - 5.6.8
    string(36) "2052-06-20 18:53:24 America/New_York" //PHP 5.3.0 - 5.3.5
    */
    ?>
    Set the timestamp from current timezone use current timezone
    <?php
    $date = new DateTime;
    $date->setTimestamp($ts); 
    var_dump($date->format('Y-m-d H:i:s e'));
    /*
    string(36) "2007-02-14 20:25:25 America/New_York" //PHP 5.3.0 - 5.6.8
    */
    ?>

    PHP DateTime::setTimezone() Method

    What does DateTime::setTimezone() do?

    The PHP DateTime::setTimezone() method sets the time zone for the DateTime object.

    PHP DateTime::setTimezone() Syntax

     public DateTime::setTimezone ( DateTimeZone $timezone ) : DateTime
     date_timezone_set ( DateTime $object , DateTimeZone $timezone ) : DateTime

    PHP DateTime::setTimezone() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. timezone — A DateTimeZone object representing the desired time zone.

    PHP DateTime::setTimezone() Return Value

    The PHP DateTime::setTimezone() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::setTimezone() Working Examples

    1. DateTime::setTimeZone() example

    <?php
    $date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
    echo $date->format('Y-m-d H:i:sP') . "\n";
    $date->setTimezone(new DateTimeZone('Pacific/Chatham'));
    echo $date->format('Y-m-d H:i:sP') . "\n";
    ?>

    Output of the above code:

    2000-01-01 00:00:00+12:00
    2000-01-01 01:45:00+13:45

    Changelog for PHP DateTime::setTimezone() Method

    5.3.0 — Changed the return value on success from NULL to DateTime.

    Additional Tips from Fellow Developers

    Contributed By: jamsilver

    In response to the other comments expressing surprise that changing the timezone does not affect the timestamp:
    A UNIX timestamp is defined as the number of seconds that have elapsed since 00:00:00 (UTC), Thursday, 1 January 1970.
    So: with respect to UTC. Always.
    Calling setTimezone() never changes the actual "absolute", underlying, moment-in-time itself. It only changes the timezone you wish to "view" that moment "from". Consider the following:
    <?php
    // A time in London.
    $datetime = new DateTime('2015-06-22T10:40:25', new DateTimeZone('Europe/London'));
    // I wonder how that SAME moment-in-time would 
    // be described in other places around the world.
    $datetime->setTimezone(new DateTimeZone('Australia/Sydney'));
    print $datetime->format('Y-m-d H:i:s (e)');
      // 2015-06-22 19:40:25 (Australia/Sydney)
    $datetime->setTimezone(new DateTimeZone('America/New_York'));
    print $datetime->format('Y-m-d H:i:s (e)');
      // 2015-06-22 05:40:25 (America/New_York)
    $datetime->setTimezone(new DateTimeZone('Asia/Calcutta'));
    print $datetime->format('Y-m-d H:i:s (e)');
      // 2015-06-22 15:10:25 (Asia/Calcutta)
    ?>
    Please note that ALL of these date strings unambiguously represent the exact same moment-in-time. Therefore, calling getTimestamp() at any stage will return the same result:
    <?php
    $datetime->getTimestamp();
      // 1434966025
    ?>

    PHP DateTime::__set_state() Method

    What does DateTime::__set_state() do?

    The PHP DateTime::__set_state() method the __set_state handler.

    PHP DateTime::__set_state() Syntax

     public static DateTime::__set_state ( array $array ) : DateTime

    PHP DateTime::__set_state() Parameters

    1. array — Initialization array.

    PHP DateTime::__set_state() Return Value

    The PHP DateTime::__set_state() method returns a new instance of a DateTime object.

    PHP DateTime::sub() Method

    What does DateTime::sub() do?

    The PHP DateTime::sub() method subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object .

    PHP DateTime::sub() Syntax

     public DateTime::sub ( DateInterval $interval ) : DateTime
     date_sub ( DateTime $object , DateInterval $interval ) : DateTime

    PHP DateTime::sub() Parameters

    1. object — Procedural style only: A DateTime object returned by date_create(). The function modifies this object.

    2. interval — A DateInterval object

    PHP DateTime::sub() Return Value

    The PHP DateTime::sub() method returns the DateTime object for method chaining or FALSE on failure.

    PHP DateTime::sub() Working Examples

    1. DateTime::sub() example

    <?php
    $date = new DateTime('2000-01-20');
    $date->sub(new DateInterval('P10D'));
    echo $date->format('Y-m-d') . "\n";
    ?>

    Output of the above code:

    2000-01-10

    2. Further DateTime::sub() examples

    <?php
    $date = new DateTime('2000-01-20');
    $date->sub(new DateInterval('PT10H30S'));
    echo $date->format('Y-m-d H:i:s') . "\n";
    $date = new DateTime('2000-01-20');
    $date->sub(new DateInterval('P7Y5M4DT4H3M2S'));
    echo $date->format('Y-m-d H:i:s') . "\n";
    ?>

    Output of the above code:

    2000-01-19 13:59:30
    1992-08-15 19:56:58

    3. Beware when subtracting months

    <?php
    $date = new DateTime('2001-04-30');
    $interval = new DateInterval('P1M');
    $date->sub($interval);
    echo $date->format('Y-m-d') . "\n";
    $date->sub($interval);
    echo $date->format('Y-m-d') . "\n";
    ?>

    Output of the above code:

    2001-03-30
    2001-03-02

    Additional Tips from Fellow Developers

    Contributed By: Anonymous

    Note that the sub() and add() methods will modify the value of the object you're calling the method on! This is very untypical for a method that returns a value of its own type. You could misunderstand it that the method would return a new instance with the modified value, but in fact it modifies itself! This is undocumented here. (Only a side note on procedural style mentions it, but it obviously does not apply to object oriented style.)

    Rate this post —

    Very PoorPoorAverageGoodExcellent (1 votes, average: 5.00 out of 5)
    Loading...

    Tags: |

    Subscribe
    Notify of
    guest
    0 Comments
    Oldest
    Newest Most Voted
    Inline Feedbacks
    View all comments
    0%