PHPBuilder - Date Manipulation in Php Page 6



RSS Twitter
Articles Php Functions

Date Manipulation in Php - Page 6

by: Allan Kent
|
July 30, 2000

Creating a DateAdd function for PHP

As I said in the beginning - the reason for this tutorial was because I could find no function in PHP that was similar to ASP's DateDiff function. So after explaining how PHP handles date and time I though it would be cool if we ported two commonly used ASP date functions to PHP. The first one is the DateAdd function.
The DateAdd function, according the VBScript documentation I have, "Returns a date to which a specified time interval has been added."
The syntax is DateAdd (interval,number,date).
The interval is a string expression that defines the interval you want to add. For example minutes or days, the number is the number of that interval that you wish to add, and the date is the date.
Interval can be one of:
yyyyyear
qQuarter
mMonth
yDay of year
dDay
wWeekday
wwWeek of year
hHour
nMinute
sSecond

 
As far as I can tell, w,y and d do the same thing, that is add 1 day to the current date, q adds 3 months and ww adds 7 days. If I've missed some subtlety of VBScript, someone please let me know :)

<?php

function DateAdd($interval$number$date) {

    
$date_time_array getdate($date);
    
$hours $date_time_array['hours'];
    
$minutes $date_time_array['minutes'];
    
$seconds $date_time_array['seconds'];
    
$month $date_time_array['mon'];
    
$day $date_time_array['mday'];
    
$year $date_time_array['year'];

    switch (
$interval) {
    
        case 
'yyyy':
            
$year+=$number;
            break;
        case 
'q':
            
$year+=($number*3);
            break;
        case 
'm':
            
$month+=$number;
            break;
        case 
'y':
        case 
'd':
        case 
'w':
            
$day+=$number;
            break;
        case 
'ww':
            
$day+=($number*7);
            break;
        case 
'h':
            
$hours+=$number;
            break
        case 
'n':
            
$minutes+=$number;
            break;
        case 
's':
            
$seconds+=$number
            break;            
    }
       
$timestampmktime($hours,$minutes,$seconds,$month,$day,$year);
    return 
$timestamp;
}

?>
We can save that code in a file called dateadd.inc and then execute the following code:

<?php

include('dateadd.inc'); $temptime time();
echo 
strftime('%Hh%M %A %d %b',$temptime);
$temptime DateAdd('n',50,$temptime);
echo 
'&lt;p&gt;';
echo 
strftime('%Hh%M %A %d %b',$temptime);

?>
which will return to us:

15h41 Saturday 03 Jun
16h31 Saturday 03 Jun


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

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Allan Kent

Comment:



Comment:

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