-4

I'm having a table as follows to store future date,

 email               date 

 abc@gmail.com    8/10/2014

and I want to do is to find the difference between the above date and the sever date.

I'm using date("m/d/Y") to get the current date.

If date("m/d/Y") = 07/20/2014, then I need the answer as 21.

Please help me find the difference between those days using PHP & MySQL, or suggest a better way to find the difference in days.

ljacqu
  • 2,132
  • 1
  • 17
  • 21
NuwanD
  • 35
  • 4
  • This might help: http://stackoverflow.com/a/3923228/328977 – buff Jun 29 '14 at 17:23
  • 3
    possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – buff Jun 29 '14 at 17:24
  • 1
    [`DATEDIFF`](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff) – shmosel Jun 29 '14 at 17:37

3 Answers3

1

You can convert date to timestamp then calculate the days:

(int)(strtotime('8/10/2014')-strtotime('07/20/2014'))/60/60/24
dcai
  • 2,557
  • 3
  • 20
  • 37
0

The easiest way would be to store your dates as timestamps, then you could subtract the current timestamp with the one you've saved in a database.

The PHP function time() returns the current timestamp – that is the number of seconds since the 1st of January 1970. You can then format a timestamp $stamp to your liking with date('m/d/Y', $stamp), for example.

Aside from facilitating arithmetic operations with dates, you can display more or less information with timestamps by formatting them with date(), as well as show different formats (July 13, 2014 vs. 07/13/2014). If you save a date as a string, e.g. "8/10/2014", it will be very complicated for you to change the format, and it won't be possible to get the correct time, for example.

Finding how long ago in days a timestamp $stamp was to the current time is very easy:

$now = time();
$days = ($stamp - $now) / (24*3600);

Use round() to get a full number if desired (e.g. 7.2309 would simply become 7).

ljacqu
  • 2,132
  • 1
  • 17
  • 21
0

I'd personally do it using DateTime:

Select your date out into a variable. In this instance We'll call it $DBDate

$DBDateObj = DateTime::createFromFormat('j/m/Y', $DBDate);
$TodayDateObj = new DateTime();
$interval = $TodayDateObj->diff($DBDateObj);
$daysDiff = $interval->days;

In $daysDiff you should now have the difference in days.

Daryll Doyle
  • 453
  • 3
  • 13