Development

Date and Time – PHP way – part 2

Where were we? Ok., I got it 🙂 Now we gonna talk about time intervals. You know that, sometimes we need to calculate one month and a few days for example. What to do? Let’s say we start something yesterday, on 29th June 2017 and this event will continue for one month and eleven days. Don’t ask me why. So, how to calculate this period of time?

We start with the code you already know:


The result is very easy to predict. Then, let’s clone $start_date object as $end_date and add date period to $end_date object like this:

Results are:

So, we know that one month and eleven days later will be 9th August. Of course we may calculate it in the opposite direction, using sub method on cloned object. Our possibilities are virtually unlimited.

So, let’s write something more about DateInterval class, mainly let’s write more about constructor and it’s time format. P means period of time. We may use years, months, days, hours, minutes, seconds. We have to use proper designator, Y for number of years, M (months), D (days), H (hours), I (minutes), S (seconds), F (microseconds, as a fraction of a second). F was added in PHP7.1. All of those designators are optional, except P. You must remember to use T designator for time. For example, P35S doesn’t mean 35 seconds. It will throw an exception. You have to use PT35S instead. If you want to combine designator, then use it left to right (form longer to shorter time period). “P1Y2M4D” is valid (one year, two months and four days) but “P2M1Y4D” is invalid and also will throw an exception. And one last thing: you have to use T designator only once. “P1DT2H5M10S” is valid and “P1DT2HT5M10S” is invalid and will what? Throw an exception, of course.

We talk here about add and sub methods of DateTime class. We’ve got one more – diff. Of course it is easy to figure out what this method is for. Let’s write something like this:

Results are:

You may show the results in a better way, for example:

We’ll get:

To be continued.

Leave a Reply

Your email address will not be published. Required fields are marked *