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 Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP Subtract Dates

Status
Not open for further replies.

Bobsmall

Programmer
Jul 25, 2007
9
TT
Hi Guys,

I have stored on my MySQL database 2 dates (start date and end date) in the format YYYY/MM/DD and i would like to perform a subtraction so that i can get the number of days between them. Anyone have any thoughts?

Thanks,

Rasheed
 
if you really mean this format
YYYY/MM/DD
and not YYYY-MM-DD
then the easy routes are not available.
you will have to do the subtraction programmatically or through some nested functions in mysql (assuming mysql).

Code:
$result = mysql_query("select start_date, end_date from table where uniqueID='someval'");
list($start_date, $end_date) = mysql_fetch_assoc($result);

//convert to standard format
$start_date = str_replace('/','-', $start_date);
$end_date = str_replace('/', '-', $end_date);

//convert to unix dates
$_start_date = strtotime($start_date);
$_end_date =strtotime($end_date);

echo "Difference is " .($_end_date - $_start_date) . " seconds";

or alternatively (in mysql)
Code:
Select
	DATEDIFF(
		REPLACE (end_date, '/', '-'),
		REPLACE (start_date, '/', '_')
		) AS NumDaysDifference
FROM
	table
WHERE
	uniqueID = 'somevalue';

 
Thanks jpadie for your quick response, i'll try it... it makes sense


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top