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



Bookmark and Share

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:

Code:
  1. <?php
  2. $date1 = "2007-10-25";
  3. $date2 = time();
  4.  
  5. echo "$date1 compare to $date2";
  6. ?>
Output:
  2007-10-25 compare to 1189772448  

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:
  1. <?php
  2. $date1 = "2007-10-25";
  3. $date2 = date("Y-m-d",time());
  4.  
  5. echo "$date1 compare to $date2";
  6. ?>
Output:
  2007-10-25 compare to 2007-09-14  

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:
  1. <?php
  2. $date1 = "2007-10-25";
  3. $date2 = time();
  4.  
  5. $dateArr = explode("-",$date1);
  6. $date1Int = mktime(0,0,0,$dateArr[1],$dateArr[2],$dateArr[0]) ;
  7. echo "$date1Int compare to $date2 difference is ".($date1Int-$date2);
  8. ?>
Output:
  1193263200 compare to 1189772448 difference is 3490752  

That's all.  







Tags: php date compare, php date comparison, date compare

PHP date compare - Table of contents
Step 1 - PHP date compare


Follow phpf1 on Twitter




F1 Site Family
AJAX F1
HTML F1
Java F1
JavaScript F1
PHP F1

Total time: 0.0254