PHP date compare
Home - Tutorials - Date and time
This article demonstrates some ways how you can compare dates in your PHP code.
Tutorial info:
Name: | PHP date compare |
Total steps: | 1 |
Category: | Date and time |
Level: | Beginner |
Bookmark PHP date compare

Step 1 - PHP date compare
PHP date compare
Sometimes you want to compare dates in your PHP code. However in a lot of cases it can be a problem that the date values to compare are not in the same format. This makes the comparison a bit more complex task. For example suppose the following code where we have 2 variables each contains a date value but we can not really compare them:
To solve this problem we need to convert on of the values to the other format. Maybe the easiest way is to use the string format. With the help of the date() function you can format a Unix timestamp to a date string and so you can compare the 2 values like this:
Code:
<?php $date1 = "2007-10-25"; echo "$date1 compare to $date2"; ?>
However in this case you don't know how big is the difference between the 2 dates. If you also want to know this information then it makes more sense to convert these values into the Unix timestamp format. In this case you have both dates in an integer. Comparison a difference calculation is very easy with integers. Later you can convert seconds into minutes, hours, days or as you want.
To use this solution we need to use the explode() function which helps to use to divide the date string into smaller parts. After it we have each element of the date in a separate variable and so we can use the mktime() function. This function will returns with the Unix timestamp and so we can make our further calculation. The code looks like this:
Code:
<?php $date1 = "2007-10-25"; ?>
That's all.
Tags: php date compare, php date comparison, date compare
PHP date compare - Table of contents |
---|
Step 1 - PHP date compare |