PHP DateInterval can’t have both weeks and days

PHP has some handy Date classes, including one for specifying date intervals. But you need to be wary of some idiosyncrasies, as I just found out.

When adding or subtracting date periods from DateTime objects in PHP, it can be convenient to build your date periods using the DateInterval class. The documentation for the class constructor tells you how to specify a date or time period with an interval spec string, which is quite easy to build in code.

For example, a date interval of one year can be built from a string P1Y — Period 1 Year. For two months and ten days, you would use the string P2M10D. Easy.

So for 12 weeks and 1 day, that would be P12W1D, right? Well, no. That actually gives you a period of one day. There’s a little note next to the W in the Period Designators table in the documentation:

weeks. These get converted into days, so can not be combined with D.

Yes, P12W1D is really just like saying P84D1D which boils down to… P1D. So if you want to combine weeks and days, you need to multiply your weeks by seven and add them to your days. P85D.

Basically, don’t ever use W in a DateInterval spec string if you’re combining multiple date parts together because you will risk losing all of your weeks; expand your weeks into days and add to your days, and use D instead.

The things you learn. And always the hard way, it seems.

Facebooktwittergoogle_plusredditlinkedinmailFacebooktwittergoogle_plusredditlinkedinmail