#native_company# #native_desc#

Date Manipulation in Php Page 7

By Allan Kent
on July 30, 2000

Creating a DateDiff function for PHP

OK, so that’s DateAdd out of the way. What about DateDiff now ?
DateDiff, according to the documentation, “Returns the number of intervals between two dates.”
The syntax is DateDiff(interval,date1,date2).
The intervals that it uses are the same as those that we saw in the DateAdd function. For the sake of
simplicity we’re going to gloss over a number of elements of VBScipt’s DateDiff function that would otherwise
complicate matters. In this example the optional arguments to DateDiff (that is whether the week starts on a
Monday or a Sunday) are not used. The intervals that we are going to allow are going to be “w”, “d&q, “h”, “n” and “s”.
Let’s see what we can come up with:


Function DateDiff

($interval,$date1,$date2) {

// get the number of seconds between the two dates 

$timedifference $date2 $date1;

    switch ($interval) {


$retval bcdiv($timedifference,604800);



$retval bcdiv($timedifference,86400);



$retval =bcdiv($timedifference,3600);



$retval bcdiv($timedifference,60);



$retval $timedifference;







Save that code to datediff.inc and you can try the following code:




$currenttime time();

'Current time: '.strftime('%Hh%M %A %d %b',$currenttime).'&lt;br&gt;';

$newtime DateAdd


'Time plus 50 minutes: '.

strftime('%Hh%M %A %d %b',$newtime).'&lt;br&gt;';

$temptime DateDiff('n',$currenttime,$newtime);

'Interval between two times: '.$temptime;


which, if you’ve got everything set up properly, should return:
Current time: 16h23 Saturday 03 Jun
Time plus 50 minutes: 17h13 Saturday 03 Jun
Interval between two times: 50
If you are running PHP on a unix system, you will have to compile in support for the bcmath functions.
README.BCMATH in your PHP distribution gives you the full details. PHP4 for Windows can do bcmath calculations without any special tinkering.
That’s it then for dates. You should now have all the tools you need to tackle dates and times and their practical application in PHP