Working with dates in PHP is one of those things that you either have a good handle on, you’re working on understanding, or you’re stuck in the rabbit hole of the documentation that’s in the manual.
If you’re working with WordPress, though, the chance that you’re going to need to work with dates is quite high. Nearly everything that we publish has at least one date associated with it.
This includes post, pages, custom post types, revisions, drafts, and so on.
Furthermore, there’s a chance that custom work that you need to develop with require that you find the difference in two dates using PHP. And though there are multiple ways of doing this, there’s a process that I’ve been following for something.
The Difference in Dates Using PHP
Before I walk through my example, it will help to give a bit of context. After all, whatever you’re working on is likely going to be a bit different than what I’m doing.
The general idea might still be the same so the gist of what you’re doing can still be extrapolated from the code below. But let me give a concrete example from my own work:
- I have a custom post type representing an event and the event as a post date.
- I need to know when the event starts. To do this, I define the date format using the n/j/Y format as supported by PHP and then convert this to a date using PHP’s date function.
- Next, I take today’s date (as an easy way to determine the difference in dates using PHP for this example) and convert it into a date using the same function and n/j/Y format.
- After that, I instantiate two DateTime objects and compute the difference.
If that’s not straightforward, I do recommend clicking on the above links. Otherwise, here’s the code.
Notice in the code above I’m only interested in retrieving the difference in years. You may opt to choose something different. If that’s the case, the API offered by PHP makes it easy to do that by examining the properties of the DateTime object.
But given two dates, this is a straightforward way to find the difference in dates using PHP in the context of WordPress.