PHP provides DateTime and DateInterval classes to make it easier to manipulate dates. Examples below show how to edit, add, subtract and get difference between dates.
Set dates
<?php // Create an instance of the current date & time. $dt = new DateTime(); // Set $dt to a specific date. $dt->setDate(2019, 8, 4); echo $dt->format('Y-m-d\TH:i:s.u') . "\n"; // modify() uses the same format as strtotime(). $dt->modify('+ 7 days'); echo $dt->format('c') . "\n"; $dt->modify('next month'); echo $dt->format('c') . "\n"; $dt->modify('last day of this month'); echo $dt->format('c') . "\n"; ?>
Output
2019-08-04T14:46:52.113419 2019-08-11T14:46:52-04:00 2019-09-11T14:46:52-04:00 2019-09-30T14:46:52-04:00
Add / subtract time from date
DateTime class provides add() and sub() methods to add and subtract time from date. They require a DateInterval object containing the
amount of time to add or to subtract from the date. The amount of time is set as a text string. It follows the following format.
It starts with the character P to define the interval as a period and followed by the amount of years, months, days, hours, minutes, seconds that you want.
For example, an interval string for a period of 2 years, 3 months, 4 days, 5 hours, 6 minutes and 7 seconds is P2Y3M4DT5H6M7S
. Note: Before you define time values,
you have to prefix with the T character.
<?php // Create an instance of the current date & time. $dt = new DateTime(); $dt->setDate(2019, 8, 4); $dt->setTime(0, 0, 0); // Add interval period. $interval = "P3D"; // A period of 3 days. $dt->add( new DateInterval($interval) ); echo $dt->format('c') . "\n"; // Add a period of 2years, 3months, 4days, 5hours, 6min, 7sec. $interval = "P2Y3M4DT5H6M7S"; // Prefix 'T' before time values. $dt->add( new DateInterval($interval) ); echo $dt->format('c') . "\n"; // subtract interval period. $interval = "P1Y"; // subtract 1 year. $dt->sub( new DateInterval($interval) ); echo $dt->format('c') . "\n"; ?>
Output
2019-08-07T00:00:00-04:00 2021-11-11T05:06:07-05:00 2020-11-11T05:06:07-05:00
Get difference between dates
DateTime class provides a neat method called diff() to get the difference between 2 dates. It returns a DateInterval object which contains the breakdown of the difference in years, months, days, hours, minutes, seconds, etc. Here is an example below.
<?php // 1st date. $dt_1 = new DateTime(); $dt_1->setDate(2019, 8, 23); $dt_1->setTime(6, 7, 8); // 2nd date. $dt_2 = new DateTime(); $dt_2->setDate(2017, 6, 7); $dt_2->setTime(0, 0, 0); // Get difference between dates. $diff = $dt_2->diff($dt_1); print_r( $diff ); print($diff->days); ?>
Output
DateInterval Object ( [y] => 2 [m] => 2 [d] => 16 [h] => 6 [i] => 7 [s] => 8 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 807 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 ) 807