PHP DateTime
Summary: in this tutorial, you’ll learn how to work with the date and time in an object-oriented way.
Introduction to the PHP DateTime class
PHP provides a set of date and time classes that allow you to work with the date and time in an object-oriented way.
To create a new date and time object, you use the DateTime class. For example:
$datetime = new DateTime(); var_dump($datetime);
Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-15 06:30:40.294788" ["timezone_type"]=> int(3) ["timezone"]=> string(13) "Europe/Berlin" >
Code language: PHP (php)
The DateTime object represents the current date and time in the timezone specified in the PHP configuration file ( php.ini )
To set a new timezone, you create a new DateTimeZone object and pass it to the setTimezone() method of the DateTime object:
$datetime = new DateTime(); $timezone = new DateTimeZone('America/Los_Angeles'); $datetime->setTimezone($timezone); var_dump($datetime);
Code language: PHP (php)
object(DateTime)#1 (3) ["date"]=> string(26) "2021-07-14 21:33:27.986925" ["timezone_type"]=> int(3) ["timezone"]=> string(19) "America/Los_Angeles" >
Code language: PHP (php)
In this example, we create a new DateTimeZone object and set it to «America/Los_Angeles» . To get valid timezones supported by PHP, check out the timezone list.
To format a DateTime object, you use the format() method. The format string parameters are the same as those you use for the date() function. For example:
$datetime = new DateTime(); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
07/15/2021 6:38 AM
Code language: PHP (php)
To set a specific date and time, you can pass a date & time string to the DateTime() constructor like this:
$datetime = new DateTime('12/31/2019 12:00 PM'); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
Or you can use the setDate() function to set a date:
$datetime = new DateTime(); $datetime->setDate(2020, 5, 1); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
05/01/2020 6:42 AM
Code language: PHP (php)
The time is derived from the current time. To set the time, you use the setTime() function:
$datetime = new DateTime(); $datetime->setDate(2020, 5, 1); $datetime->setTime(5, 30, 0); echo $datetime->format('m/d/Y g:i A');
Code language: PHP (php)
05/01/2020 5:30 AM
Code language: PHP (php)
Since the setDate() , setTime() , and setTimeZone() method returns the DateTime object, you can chain them like this which is quite convenient.
$datetime = new DateTime(); echo $datetime->setDate(2020, 5, 1) ->setTime(5, 30) ->setTimezone(new DateTimeZone('America/New_York')) ->format('m/d/Y g:i A');
Code language: PHP (php)
04/30/2020 11:30 PM
Code language: PHP (php)
Creating a DateTime object from a string
When you pass the date string ’06/08/2021′ to the DateTime() constructor or setDate() function, PHP interprets it as m/d/Y . For example:
$datetime = new DateTime('06/08/2021'); echo $datetime->format('F jS, Y');
Code language: PHP (php)
June 8th, 2021
Code language: PHP (php)
If you want to pass it as August 6th, 2021, you need to use the – or . instead of /. For example:
$datetime = new DateTime('06-08-2021'); echo $datetime->format('F jS, Y');
Code language: PHP (php)
August 6th, 2021
Code language: PHP (php)
However, if you want to parse the date string ’06/08/2021′ as d/m/Y, you need to replace the / with – or . manually:
$ds = '06/08/2021'; $datetime = new DateTime(str_replace('/', '-', $ds)); echo $datetime->format('F jS, Y');
Code language: PHP (php)
August 6th, 2021
Code language: PHP (php)
A better way to do it is to use the createFromFormat() static method of the DateTime object:
$ds = '06/08/2021'; $datetime = DateTime::createFromFormat('d/m/Y', $ds); echo $datetime->format('F jS, Y');
Code language: PHP (php)
In this example, we pass the date format as the first argument and the date string as the second argument.
Note that when you pass a date string without the time, the DateTime() constructor uses midnight time. However, the createFromFormat() method uses the current time.
Comparing two DateTime objects
PHP allows you to compare two DateTime objects using the comparison operators including >, >=, . For example:
$datetime1 = new DateTime('01/01/2021 10:00 AM'); $datetime2 = new DateTime('01/01/2021 09:00 AM'); var_dump($datetime1 < $datetime2); // false var_dump($datetime1 > $datetime2); // true var_dump($datetime1 == $datetime2); // false var_dump($datetime1 $datetime2); // 1
Code language: PHP (php)
Calculating the differences between two DateTime objects
The diff() method of the DateTime() object returns the difference between two DateTime() objects as a DateInterval object. For example:
$dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); $age = $to_date->diff($dob); var_dump($age);
Code language: PHP (php)
object(DateInterval)#3 (16) ["y"]=> int(31) ["m"]=> int(6) ["d"]=> int(14) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(1) ["days"]=> int(11518) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) >
Code language: PHP (php)
The DateInterval represents the differences between two dates in the year, month, day, hour, etc. To format the difference, you use the DateInterval ‘s format. For example:
$dob = new DateTime('01/01/1990'); $to_date = new DateTime('07/15/2021'); echo $to_date->diff($dob)->format('%Y years, %m months, %d days');
Code language: PHP (php)
31 years, 6 months, 14 days
Code language: PHP (php)
Adding an interval to a DateTime object
To add an interval to date, you create a new DateInterval object and pass it to the add() method. The following example adds 1 year 2 months to the date 01/01/2021 :
$datetime = new DateTime('01/01/2021'); $datetime->add(new DateInterval('P1Y2M')); echo $datetime->format('m/d/Y');
Code language: PHP (php)
03/01/2022
Code language: PHP (php)
To format a date interval, you use the date interval format strings.
To subtract an interval from a DateTime object, you create a negative interval and use the add() method.
Summary
- Use the DateTime class to work with the date and time.
- Use the DateTimeZone class to work with time zones.
- Use the comparison operators to compare two DateTime objects.
- Use the diff() method to calculate the difference between to DateTime objects.
- Use the DateInterval class to represent a date and time interval.
- Use the add() method to add an interval to or subtract an interval from a DateTime object.
Переменные формата даты php
This page describes the different date formats in a BNF-like syntax, that the DateTimeImmutable , DateTime , date_create() , date_create_immutable() , and strtotime() parser understands.
To format DateTimeImmutable and DateTime objects, please refer to the documentation of the DateTimeInterface::format() method.
Description | Format | Examples |
---|---|---|
daysuf | «st» | «nd» | «rd» | «th» | |
dd | (1?5 | «3»[01]) daysuf ? | «7th», «22nd», «31» |
DD | «0» 5 | 13 | «3» [01] | «07», «31» |
m | ‘january’ | ‘february’ | ‘march’ | ‘april’ | ‘may’ | ‘june’ | ‘july’ | ‘august’ | ‘september’ | ‘october’ | ‘november’ | ‘december’ | ‘jan’ | ‘feb’ | ‘mar’ | ‘apr’ | ‘may’ | ‘jun’ | ‘jul’ | ‘aug’ | ‘sep’ | ‘sept’ | ‘oct’ | ‘nov’ | ‘dec’ | «I» | «II» | «III» | «IV» | «V» | «VI» | «VII» | «VIII» | «IX» | «X» | «XI» | «XII» | |
M | ‘jan’ | ‘feb’ | ‘mar’ | ‘apr’ | ‘may’ | ‘jun’ | ‘jul’ | ‘aug’ | ‘sep’ | ‘sept’ | ‘oct’ | ‘nov’ | ‘dec’ | |
mm | «0»? 4 | «1»2 | «0», «04», «7», «12» |
MM | «0» 6 | «1»2 | «00», «04», «07», «12» |
y | 3 | «00», «78», «08», «8», «2008» |
yy | 6 | «00», «08», «78» |
YY | 8 | «2000», «2008», «1978» |
YYY | 6 | «81412», «20192» |
Description | Format | Examples |
---|---|---|
American month and day | mm «/» dd | «5/12», «10/27» |
American month, day and year | mm «/» dd «/» y | «12/22/78», «1/17/2006», «1/17/6» |
Four digit year, month and day with slashes | YY «/» mm «/» dd | «2008/6/30», «1978/12/22» |
Four digit year and month (GNU) | YY «-» mm | «2008-6», «2008-06», «1978-12» |
Year, month and day with dashes | y «-» mm «-» dd | «2008-6-30», «78-12-22», «8-6-21» |
Day, month and four digit year, with dots, tabs or dashes | dd [.\t-] mm [.-] YY | «30-6-2008», «22.12.1978» |
Day, month and two digit year, with dots or tabs | dd [.\t] mm «.» yy | «30.6.08», «22\t12.78» |
Day, textual month and year | dd ([ \t.-])* m ([ \t.-])* y | «30-June 2008», «22DEC78», «14 III 1879» |
Textual month and four digit year (Day reset to 1) | m ([ \t.-])* YY | «June 2008», «DEC1978», «March 1879» |
Four digit year and textual month (Day reset to 1) | YY ([ \t.-])* m | «2008 June», «1978-XII», «1879.MArCH» |
Textual month, day and year | m ([ .\t-])* dd [,.stndrh\t ]+ y | «July 1st, 2008», «April 17, 1790», «May.9,78» |
Textual month and day | m ([ .\t-])* dd [,.stndrh\t ]* | «July 1st,», «Apr 17», «May.9» |
Day and textual month | dd ([ .\t-])* m | «1 July», «17 Apr», «9.May» |
Month abbreviation, day and year | M «-» DD «-» y | «May-09-78», «Apr-17-1790» |
Year, month abbreviation and day | y «-» M «-» DD | «78-Dec-22», «1814-MAY-17» |
Year (and just the year) | YY | «1978», «2008» |
Year (expanded, 5-19 digits with sign) | [+-] YYY | «-81120», «+20192» |
Textual month (and just the month) | m | «March», «jun», «DEC» |
Description | Format | Examples |
---|---|---|
Eight digit year, month and day | YY MM DD | «15810726», «19780417», «18140517» |
Four digit year, month and day with slashes | YY «/» MM «/» DD | «2008/06/30», «1978/12/22» |
Two digit year, month and day with dashes | yy «-» MM «-» DD | «08-06-30», «78-12-22» |
Four digit year with optional sign, month and day | [+-]? YY «-» MM «-» DD | «-0002-07-26», «+1978-04-17», «1814-05-17» |
Five+ digit year with required sign, month and day | [+-] YYY «-» MM «-» DD | «-81120-02-26», «+20192-04-17» |
Note:
For the y and yy formats, years below 100 are handled in a special way when the y or yy symbol is used. If the year falls in the range 0 (inclusive) to 69 (inclusive), 2000 is added. If the year falls in the range 70 (inclusive) to 99 (inclusive) then 1900 is added. This means that «00-01-01» is interpreted as «2000-01-01».
Note:
The «Day, month and two digit year, with dots or tabs» format ( dd [.\t] mm «.» yy ) only works for the year values 61 (inclusive) to 99 (inclusive) — outside those years the time format » HH [.:] MM [.:] SS » has precedence.
Note:
The «Year (and just the year)» format only works if a time string has already been found — otherwise this format is recognised as HH MM .
It is possible to over- and underflow the dd and DD format. Day 0 means the last day of previous month, whereas overflows count into the next month. This makes «2008-08-00» equivalent to «2008-07-31» and «2008-06-31» equivalent to «2008-07-01» (June only has 30 days).
Note that the day range is restricted to 0-31 as indicated by the regular expression above. Thus «2008-06-32» is not a valid date string, for instance.
It is also possible to underflow the mm and MM formats with the value 0. A month value of 0 means December of the previous year. As example «2008-00-22» is equivalent to «2007-12-22».
If you combine the previous two facts and underflow both the day and the month, the following happens: «2008-00-00» first gets converted to «2007-12-00» which then gets converted to «2007-11-30». This also happens with the string «0000-00-00», which gets transformed into «-0001-11-30» (the year -1 in the ISO 8601 calendar, which is 2 BC in the proleptic Gregorian calendar).