Page 1 of 1

Calculating the difference betweek two dates

Posted: Mon May 15, 2006 6:35 am
by mhouldridge
Hi,

I am trying to calculate the numbe rof days between today's date and a future date, for end dates on evaluation software.

Here is my code;

Code: Select all

// Database query
$sql = mysql_query("SELECT * FROM software WHERE trial = 'YES'"); 
$row = mysql_fetch_array($sql);

// Set variable $today to today's date
$today = date("Y-m-d"); // Set today's date as variable

//set date two variable to the field value of end_date from the query
$datetwo = $row['end_date'];

// Set variable for number of evaluation days left
$daysleft = ((strtotime($datetwo) - strtotime($today))/86400);
The problem I have with the above is that the $daysleft shows the dates with decimal places, and they are not correct.

Please help

Posted: Mon May 15, 2006 6:47 am
by timvw
Have a look at the DATEDIFF function in DATE and TIME functions section of the MySQL manual...

(http://dev.mysql.com/doc/refman/5.0/en/ ... tions.html)

Posted: Mon May 15, 2006 6:47 am
by BadgerC82
I think this code would work but I haven't tested (I'm feeling lazy ;) ).

starttime = mktime(0,0,0, start_month, start_day, start_year);

endtime = mktime(0,0,0, end_month, end_day, end_year);

$days = (int) ((endtime - starttime) / 86400);

The (int) casts your result to the nearest integer...

Hope it works for ya.

Posted: Mon May 15, 2006 6:53 am
by BadgerC82
Yeah timv's suggestion of doing it in mysql is better :)

Posted: Mon May 15, 2006 7:46 am
by mhouldridge
Thanks for that.

I dont quite understand the mysql workaround...

My dates are stored like follows within the mysql table;

2006-02-16

year / month / day


I have sorted my script now so that it works however I do not think this is the best way of doing it;

Code: Select all

$today = date("Y-m-d"); // Set today's date as variable
$notify = 7; // Set notify variable to 7
$datetwo = $row['end_date']; //set dattwo variable to the field value from the query
$daysleft = (int)((strtotime($datetwo) - strtotime($today))/86400); 
if ($daysleft <= 7){
As you can see I have rounded the days off to the nearest integar..... I was thinking about tweeking this for a subscription system... but dont know if I can trust it completely.

Posted: Mon May 15, 2006 8:27 am
by BadgerC82
The code you have should definitly work but the Mysql solution is more elegant:

Code: Select all

$query = "SELECT software.*, DATEDIFF('1997-12-31', software.end_date) as date_difference FROM this_table WHERE trial = 'YES'";
This should work... I hope ;)

Posted: Mon May 15, 2006 8:55 am
by mhouldridge
Yes,

I thought it would be along those lines...

Many thanks for your workaround, I think mySQL would be a better way of doing it.