RE: subtracting dates...

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I found this code at Google's cached version of the manual for the
date() function:
http://216.239.37.104/search?q=cache:kq0aNfZeEp8J:www.php.net/date+diffe
rence+two+date+site:www.php.net&hl=en&ie=UTF-8

This code only returned the number of hours, minutes, and seconds
between the two points in time.  Now it returns years and days as well
as the left over time.  The script also used the mod operator (%) to
find the remaining days after determining the year and it would not
calculate correctly.  For example, if I compared yesterday, three years
ago(08-01-00) and today (08-02-03) at noon for both days, I would get a
difference of 3 years.  No I am using while loops subtracting whole
years to find the number of days that remain.  The same is true for
subtracting days, hours and minutes.

CODE:
<?php

$diff = dateDiff("12-21-1983 10:20:00", "08-02-2003 16:42:01");
echo "$diff\r\n";

function unixTm($strDT)
{
	$arrDT = explode(" ", $strDT);
	$arrD = explode("-", $arrDT[0]);
	$arrT = explode(":", $arrDT[1]);
	return mktime($arrT[0], $arrT[1], $arrT[2], $arrD[0], $arrD[1],
$arrD[2]);
}

function dateDiff($date1,$date2)
//       dateDiff(date_in_the_past, date_in_the_future)
{
	$dt2=unixTm($date2) ;
	$dt1=unixTm($date1) ;
	$r =  $dt2 - $dt1;
	
	$yy=floor($r / 31536000);
	while ($r > 31536000){
		$r -= 31536000;
	}
	$dd=floor($r / 86400);
	while ($r > 86400){
		$r -= 86400;
	}
	$hh=floor($r/3600);
	if ($hh<=9) $hh="0".$hh;  //adds a leading 0 if less than 10
	while ($r > 3600){
		$r -= 3600;
	}
	$mm=floor($r/60);
	if ($mm<=9) $mm="0".$mm; //adds a leading 0 if less than 10
	while ($r > 60){
		$r -= 60;
	}
	$ss=$r ;
	if ($ss<=9) $ss="0".$ss; //adds a leading 0 if less than 10
	$retval="$yy year(s), $dd day(s) $hh:$mm:$ss";
	return $retval;
}

?>


OUTPUT:
19 year(s), 229 day(s) 05:22:01

Hope this helps,
Ryan Marks

-----Original Message-----
From: John Ryan [mailto:celticfc@iol.ie] 
Sent: Saturday, August 02, 2003 2:31 PM
To: php-general@lists.php.net; php-db@lists.php.net
Subject:  subtracting dates...


Hi,

In mySQL, I store dates as YYYY-MM-DD, a standard DATE type. It stores
users date of births. I need to calculate in a PHP script, the users age
from this DOB. I get a PHP date in the same format as the mySQL and
subtract, which returns the year rounded off. ie, it doesnt matter if
your birthdays in june of 1983 and the date is januray 2003, your age is
still returned as 20, when it should be 19.

Does anyone know how can i get the right age?



-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


-- 
PHP Database Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [PHP Users]     [Postgresql Discussion]     [Kernel Newbies]     [Postgresql]     [Yosemite News]

  Powered by Linux