PHPBuilder - Date Manipulation in Php Page 7



RSS Twitter
Articles Php Functions

Date Manipulation in Php - Page 7

by: Allan Kent
|
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:

<?php

Function DateDiff
($interval,$date1,$date2) {
    
// get the number of seconds between the two dates 
$timedifference $date2 $date1;

    switch (
$interval) {
        case 
'w':
            
$retval bcdiv($timedifference,604800);
            break;
        case 
'd':
            
$retval bcdiv($timedifference,86400);
            break;
        case 
'h':
            
$retval =bcdiv($timedifference,3600);
            break
        case 
'n':
            
$retval bcdiv($timedifference,60);
            break;
        case 
's':
            
$retval $timedifference;
            break;
            
    }
    return 
$retval;

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

<?php

include('datediff.inc';
include(
'dateadd.inc');
$currenttime time();
echo 
'Current time: '.strftime('%Hh%M %A %d %b',$currenttime).'&lt;br&gt;';
$newtime DateAdd
('n',50,$currenttime);
echo 
'Time plus 50 minutes: '.
strftime('%Hh%M %A %d %b',$newtime).'&lt;br&gt;';
$temptime DateDiff('n',$currenttime,$newtime);
echo 
'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
--Allan

« Previous Page
1
|
2
|
3
|
4
|
5
|
6
|
7

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Allan Kent

Comment:



Comment:

(Maximum characters: 1200). You have characters left.