$date = new DateTime("2024-10-01");
$interval = new DateInterval("P1M"); // 1 month
$date->add($interval); // Adds 1 month
echo $date->format('Y-m-d'); // Output: 2024-11-01
DateInterval can be used to create a new dateinterval object for our date calculation and uses in any script. In the advance PHP object oriented style for all date & time calculations this format is useful. To specify we have to use some standards which are listed here.
The period designations are single character.
Y Year
M Month
D days
H hours
I minutes
S seconds
The total specification has to start with P and then with an integer value followed by a period designator. All time part has to start with T.P7D : 7 days
P1Y1M : One year and one month
P1Y1M2D : One year, one month and 2 Days
We need to keep the sequence as Year Month and Date , we can't keep at Month Year Date or any other way as we wish.
P1Y2D1M : This is wrong sequence
Same way we can add time also to the sequence , let us try with time only, then we will add both date and time to the sequencePT1H : Adds one hour to the present time
PT1H5M : Adds one hour 5 minutes to the present time
PT1H5M10S : Adds one hour 5 minutes 10 seconds
Here also we have to maintain the sequence as Hour Minute and seconds .
PT1M5H10S This will generate error as we have followed Minutes , Hour and second format.
Let us combine date and time both and create an interval object
P1Y2M5DT1H5M10S This will set an interval of 1 Year , 2 Months, 5 Days , 1 Hour, 5 Minutes, 10 Seconds
$date = new DateTime('2012-02-01 13:25:50');
echo $date->format('Y-m-d H:i:s') . "<br>";
$date->add(new DateInterval('P1Y2M5DT1H5M10S'));
echo $date->format('Y-m-d H:i:s') . "\n";
The output of above code is here
2012-02-01 13:25:50
2013-04-06 14:31:00
$date = new DateTime(); // Todays date
Output ( Refresh this page and see the changes ) 2027-11-14 18:01:48
PHP Date Functions
Date Difference
Timestamp in PHP Displaying calendar for selection of date by user
Formatting the date interval in date and time
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.