PHP Date Calculation

May 07, 2008

It is interesting when comes to the topic on calculating the date difference between two given date.  The easiest and most straight forward method will be :

  1. Convert both date into seconds since Unix EPOCH (January 1 1970 00:00:00 GMT)
  2. Do the calculation by using simple arithmethic “-” calculation.
  3. Convert the differences back to number of days

Convert Date into Seconds since Unix EPOCH

To convert it you may either use date() function by passing “U” to its first parameters. Or, you may consider to use mktime() function. Use the date() function when you plan to to capture the seconds of the current date or if you do have a timestamp ready to be passed to the second parameters.

If you wish to do calculation from the data posted from the HTML forms, I would suggest that you use mktime() and explode().

Use explode() function to extract out the day, month, and year into a single array storage. Then use mktime() function to create a Unix timestamp (in seconds) for both date.

Convert the differences back to number of days

Once you have done the calculation of the difference between date using arithmathic calculation, the results will be seconds. To convert to number of days, you will need to do conversion by using normal time conversion algorithm where:

1 day = 60×60x24

Converting to number of months or years may be challenging. You may consider to fix that 1 month is 30 days and 1 year is 365 days to ease your work.

Assume that $date1 and $date2 is the variables posted from the HTML form, below are the sample scripts:

$date1 = “1-1-2008″; //using dd-mm-yyyy format
$date2 = “5-1-2008″; //using dd-mm-yyyy format

$date1 = explode(”-”,$date1);
$date2 = explode(”-”,$date2);

$date1 = mktime(0,0,0,$date1[1],$date1[0],$date1[2]);
$date2 = mktime(0,0,0,$date2[1],$date2[0],$date2[2]);

$datedifference = $date2 - $date1;

echo(”This difference of the date are “.$datedifference/(60*60*24).” days”);

 

You may click here to download the sample source.

Leave a Reply