How to compare Dates in PHP?

How to compare Dates in PHP?

In the old days of PHP, we used to compare dates using strtotime(). Since, strtotime converts the given date to the Unix Timestamp i.e. Number of seconds from the epoch, we can then do the basic maths like add, diff, compare with the integers (no of seconds) and then can convert back the unix timestamp to date using date function. e.g.

The Old way. (using strtotime)

Compare Dates

How to Subtract Dates in PHP?

But that’s all Old fashioned and have few limitations. Since strtotime returns number of seconds from epoch in Integer and we know that Integers have a limit. As per PHP documentation, The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)

So, let’s have a look at the new way:

The New Way or rather better (Using PHP’s DateTime class)

Note: As per PHP documentation, We need PHP >= 5.3.0 to use DateTime class.

So, Now let’s have a look at How to compare dates using PHP’s DateTime?

How to calculate the difference between two dates using PHP?

We will use DateTime Class diff method that return the DateInterval. Read more about DateInterval, here.

So that’s about Comparing Dates in PHP, Hope you like it.
We will talk about “Dates in PHP” in general in further posts. Till than stay tuned and Happy Coding !!

Leave a Reply

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