Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Date Diff 3

Status
Not open for further replies.

ScottCybak

Programmer
Sep 29, 2000
48
CA
How do i compare 2 dates, and find the number of days between them?

I've searched the PHP online manual (php.net/manual/en) and also the MySQL documentation, but have found none.

Thanks in advance! Scott Cybak
scott@athree.com
 
Well, it depends on the format of the date.

For example, if you had a date like:

[tt]
Monday, January 22, 2001 12:24:32 am
[/tt]

Or something like that, it would be pretty hard beacuse you can't just do subtraction, you would have to find the day (22) and then find the new day, and subtract them. Not easy.

But like you said, I am not sure if there are any PHP functions to do this. There is a mysql function called TO_DAYS() that finds the number of days to a date. For example, you could have something like this:

[tt]
SELECT something FROM table WHERE TO_DAYS(NOW()) - TO_DAYS(date_col) <= 30;
[/tt]

That would select all of the rows that have a date in between now and 30 days ago. But that is provided you have a date using the mysql DATE data type, so the format is:

yyyy-mm-dd

Hope this helps.
-Vic
vic cherubini
krs-one@cnunited.com
====
Knows: Perl, HTML, JavScript, C/C++, PHP, Flash
====
 
Well, I must say that I don't know how you can come up with a data like that without having used some kind of formulation/function to begin with (such as date() or in MySQL - NOW()).

If you are pulling the data from mysql and are using a DATETIME or DATE fieldtype, there are dozens of wonderful functions you can use to find the difference in dates using SQL.

If you are doing the diff in PHP, you can use mktime().

Here is a sample comparing your date above and another date (should be 24 hours, 35 minutes, and 21 seconds):

Code:
<?php
/*
  hour,minute,secone,month,day,year.
*/
$date1 = mktime(0,24,32,1,22,2001);
$date2 = mktime(0,25,31,1,23,2001);
$diff = $date2-$date1;

//get number of hours
$hours = $diff / 60 / 60;

//if there are fractional hours left over...
if($diff % 60) {
$minutes = $diff % 60 * 60 / 100;
}

//if there are fractional minutes left over...
if($minutes % 60) {
     $seconds = $minutes % 60 * 60 / 100;
}

//and output...
echo floor($hours).&quot; hours, &quot;.floor($minutes).&quot; minutes, &quot;.floor($seconds).&quot; seconds&quot;;
?>

Hope this gets you on your way! ICQ: 54380631
 
Thanks, works like a charm. You get a star! Scott Cybak
scott@athree.com
 
I think inlandpac's post is quite helpful. Great example with a solution that so many people are looking for!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top