datediff

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
spitfire_esquive
Forum Commoner
Posts: 37
Joined: Sun Nov 06, 2005 6:46 am

datediff

Post by spitfire_esquive »

does anyone know of a php function or script out there that would mimic datediff? *its a function that calculates the difference between two dates to day, minutes, seconds*. or should i try pear?

thank you! :D
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

This isn't a Code Snipplet..

Moved to PHP-Code.
User avatar
raghavan20
DevNet Resident
Posts: 1451
Joined: Sat Jun 11, 2005 6:57 am
Location: London, UK
Contact:

Post by raghavan20 »

This should help you calculate the number of days between two dates...be careful about formats to be used.

Code: Select all

<?php
/**
Provide from and to dates
While providing dates you can use any of these two formats:
format 1: mm/dd/yyyy
format 2: 10 September 2000
**/

$from_date = "9/9/1998";
$to_date = "10 September 1999";
echo "<br />".floor((strtotime($to_date) - strtotime($from_date))/(60*60*24))."<br />";
dateDifference($from_date, $to_date);
?>

<?php
function dateDifference($from_date, $to_date){
	echo "<br />Number of days: ".floor((strtotime($to_date) - strtotime($from_date))/(60*60*24))."<br 

/>";
}
?>
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Post by dude81 »

If you Can pass tow dates as arguments with time to the functiona and parse them within the function you can get best results
.Though code is long it is works very fine.

I used strtotime but it gave once a problem when Im dealing with it.
It has some problem with the starting day of a everynew year. So I developed this complex function

Code: Select all

function datediff(){
$opening_time =  mktime(OpeningHourHere, Openingminute, OpeningSeciondHere, OpeningmonthHere, OpeningDayhere, OpeningYearhere, Standardoftimehere);
$close_time =  mktime(ClosingHourHere,Closingminuteminute,........,Standardoftime ]);;
$diff = ceil(($opening_time-close_time) / (1 * 24 * 60 * 60));
return $diff;
}
User avatar
m3mn0n
PHP Evangelist
Posts: 3548
Joined: Tue Aug 13, 2002 3:35 pm
Location: Calgary, Canada

Post by m3mn0n »

http://php.net/date has some helpful code snippets in the user comments.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

Nevermind. I didn't realize strtotime took leap years into account.
Post Reply