0

Problem: The output is wrong despite that in DB is correct (timestamp)

Screenshot of DB: http://prntscr.com/mjftzn

The code is the output

    $dbDate = strtotime(date('Y-m-d H:i:s')); // Database date
    $endDate =  strtotime("".$query['duedate']."");    // current time
    $diff = $endDate - $dbDate; /// diffrence
     $days = intval(intval($diff) / (3600*24));
$newDays = $days < 0 ? 'EXPIRED' : $days;

Result of code: http://prntscr.com/mjfw4t

Expected: 14 day remaining instead of expired, if -1 it will show expired

Mike Doe
  • 16,349
  • 11
  • 65
  • 88
VoxVola
  • 59
  • 1
  • 1
  • 8

3 Answers3

1

This is how you can calculate difference between two dates:

$date1 = "2007-03-24";
$date2 = "2009-06-26";

$diff = abs(strtotime($date2) - strtotime($date1));

$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));


printf("%d years, %d months, %d days\n", $years, $months, $days);

Now implement it with your own logic.

saibbyweb
  • 2,864
  • 2
  • 27
  • 48
0

When working with dates and time in PHP a lot of what you want to do is handled by DateTime library. An extension to this that I have ended up using a lot is Carbon which provides a lot of functions to calculate differences, intervals and also turn it into human-readable form etc.

Using Carbon you could write something like this.

$days    = Carbon::parse(date('Y-m-d H:i:s'))->diffInDays(Carbon::parse($query['duedate']));
$newDays = $days < 0 ? 'EXPIRED' : $days;

But since you seem to just use the current time as the "database date" you could use Carbon::now() instead of parsing the string provided by date() into a Carbon object.

inquam
  • 12,664
  • 15
  • 61
  • 101
  • @treyBake: For seemingly simple things I tend to want to help people find the answer, read and understand it :). Updated with a small piece of code though. Although the initial code provided seems a bit strange since the op's "database date" seems to be the current time. But op probably knows how the logic of the system is supposed to work. – inquam Feb 11 '19 at 09:36
0

You can do this in Database. Use something like

SELECT duedate>NOW() as expired; 
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Benni
  • 69
  • 1
  • 4