Date and time manipulation in PHP is mostly connected with functions like: date, time or strtotime. They can be sufficient, but if we want to deal with dates like with objects – we can use DateTime class. DateTime class is not only straightforward wrapper for standard functions, it has a lot of additional features – for example timezones.
Date creation
public DateTime::__construct() ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] )
During DateTime object creation we can set time and timezone. Time can be represented as one of supported formats
Date and time formats examples:
$date = new DateTime('2011-08-07 10:20:30'); print $date->format('d-m-Y H:i'); # 07-08-2011 10-20 print PHP_EOL; $date = new DateTime('@223311122'); print $date->format('d-m-Y H:i'); # 28-01-1977 14-52 print PHP_EOL; $date = new DateTime('9/24/72 12:20'); print $date->format('d-m-Y H:i'); # 24-09-1972 12-20 print PHP_EOL;
Notice: When using timestamp notation (@TIMESTAMP) – timezone is ignored
If we don’t set timezone, the current timezone will be use.
Format date
Date is formatted by format method. It takes one parameter, format, which is format accepted by date function. Examples can be found above.
Date Comparison
We can compare DateTime objects with PHP comparison operators.
$dateA = new DateTime('2011-07-05'); $dateB = new DateTime('2011-07-07'); var_dump($dateA > $dateB); # false var_dump($dateA < $dateB); # true
Altering date
DateTime object is mutable – it means that we can change date or time after creation. We can change date or time with setDate(), setTime() or setTimestamp() methods.
$date = new DateTime(); $date->setDate(2010, 11, 12); $date->setTime(15, 10); print $date->format('d-m-Y H:i'); #12-11-2010 15:10
Another possibility for altering date are sub and add methods – for respectively subtracting and adding date interval to our object. These methods takes DateInterval object as argument. According to documentation, DateInterval is:
Representation of date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTime’s constructor supports.
Example of using 2 days interval.
$date = new DateTime('2011-10-10'); $date->add(new DateInterval('P2D')); print $date->format('d-m-Y'); #12-10-2010 print PHP_EOL; $date = new DateTime('2011-10-10'); $date->sub(new DateInterval('P2D')); print $date->format('d-m-Y'); #08-10-2010
More information about creating DateInterval object can be found here. DateInterval has also static method createFromDateString, which can create DateInterval object from relative parts of date string, as show below.
$dateInterval = DateInterval::createFromDateString('2 days');
We can also increment or decrement DateTime object using modify method.
$date = new DateTime('2011-10-10'); $date->modify('+1day'); print $date->format('d-m-Y'); #11-10-2010
Modify accepts strtotime format.
Notice: Sometimes modify can behave unintuitive. Derick Rethans wrote article about one such case.
Above methods return $this – so they can be used for method chaining.
$date = new DateTime(); $date->setDate(2010, 11, 12)->setTime(15, 10); print $date->format('d-m-Y H:i'); #12-11-2010 15:10
Calculating difference between two DateTime objects
This is one of my favorite features in DateTime class. Using diff method we can calculate difference between two DateTime objects. Diff method returns DateInterval object.
$dateA = new DateTime('2011-10-10'); $dateB = new DateTime('2011-10-12'); $interval = $dateA->diff($dateB); print $interval->format('days: %R %d'); #days: +2 $interval = $dateB->diff($dateA); print $interval->format('days: %R %d'); #days: -2
Diff method has also second optional parameter, absolute – when true is passed difference is return as absolute.
$dateA = new DateTime('2011-10-10'); $dateB = new DateTime('2011-10-12'); $interval = $dateB->diff($dateA); print $interval->format('days: %R %d'); #days: -2 print PHP_EOL; $interval = $dateB->diff($dateA, true); print $interval->format('days: %R %d'); #days: +2
Iterating through date period
Another interesting class is DatePeriod, which can be used for iterating through some period of time. We can set start date (DateTime), interval for iterating (DateInterval), and optionally end date (DateTime). It can be really useful.
$dateStart = new DateTime('2011-10-10 10:00'); $dateEnd = new DateTime('2011-10-10 14:00'); $periodInterval = new DateInterval('PT1H'); $datePeriod = new DatePeriod($dateStart, $periodInterval, $dateEnd); foreach ($datePeriod as $hourPeriod) { print $hourPeriod->format('d-m-Y H:i'); print PHP_EOL; } # 10-10-2011 10:00 # 10-10-2011 11:00 # 10-10-2011 12:00 # 10-10-2011 13:00
DatePeriod has more types of constructors and can be used in completely different way.
[...] Lukasiewicz hat eine neue Nachricht heute über Arbeiten mit Daten und Zeiten in PHP auf einer objektorientierten Weise als in den traditionell verfahrensrechtlichen Weg des gerechten [...]
php now also includes i18n support for rendering and parsing dates : intldateformatter
Good post !
@yoye
intldateformatter is indeed interesting class, thanks for hint!
Hi,
is it possible to set a Date after 2038 ?
@John S.
It is possible, but getTimestamp() will return false.
$dateAfter2038 = new DateTime(’2039-05-10′);
var_dump($dateAfter2038->format(‘d-m-Y’));
# 10-05-2039
var_dump($dateAfter2038->getTimestamp());
# false
[...] neu ist), die zu wenig Beachtung finden. Eine von ihnen sind die Datums- und Zeitklassen rund um DateTime. Left Join frischt auf, was vielleicht in einem hinteren Hirnlappen verstaubt.Website-AnalyseIhr [...]