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.
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.
Example : 4 days can be specified as P4D. Here are some more examples of datetime interval specifications
P7D : 7 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.
P1Y1M : One year and one month
P1Y1M2D : One year, one month and 2 Days
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 sequence
PT1H : Adds one hour to the present time
Let us combine date and time both and create an interval object
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.
P1Y2M5DT1H5M10S This will set an interval of 1 Year , 2 Months, 5 Days , 1 Hour, 5 Minutes, 10 Seconds
Adding date interval to date object
We will try to add the above interval to a new date object. Here is the php script.
$date = new DateTime('2012-02-01 13:25:50');
The output of above code is here
echo $date->format('Y-m-d H:i:s') . "<br>";
echo $date->format('Y-m-d H:i:s') . "\n";