-2

I have make this code for getting difference between two date but it does not work properly. How can correct this code please do some help me.

  • In my database last login time saved as below

2015-01-23 15:28:05

2015-01-23 15:28:07

2015-01-23 15:29:24

2015-01-23 15:28:01

This is code i have written

$sql="SELECT * FROM users";
$sql_query=mysql_query($sql);
$cur_date=date('Y-m-d H:i:s');

while($data=mysql_fetch_array($sql_query))
{

$last_date=$data['last_login_time'];
echo $last_date;
echo "<br>";

$date1 = new DateTime($last_date);
$date2 = new DateTime($cur_date);
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 
echo "<br>";
}

And output i got like this way

2015-01-23 15:28:05
difference 0 years, 0 months, 0 days
2015-01-23 15:28:07
difference 0 years, 0 months, 0 days
2015-01-23 15:29:24
difference 0 years, 0 months, 0 days
2015-01-23 15:28:01
difference 0 years, 0 months, 0 days 

Please someone help me.

Got answer i did not use interval->h, interval->i and interval->s . After using interval->h, interval->i and interval->s code works perfectly. Thanks everyone. And sorry for westing your time

  • 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) – Refilon Jan 23 '15 at 11:27
  • Hey dennis, i read that code but this does not work... Please try above code. It is not working. – Chintan Panchal Jan 23 '15 at 11:28
  • Whats your last and cur date? I think the problem is that last_date is newer than cur_date. – q0re Jan 23 '15 at 11:30
  • Probably, last_date and cur_date are on the same day. – segarci Jan 23 '15 at 11:31
  • Convert to unix timestamp, subtract earlier date from later one, then mktime() the difference as you need. – ggdx Jan 23 '15 at 11:31
  • @q0re last_date is last login time of user and cur date is current date and time. I interchange both but does not work... – Chintan Panchal Jan 23 '15 at 11:33

1 Answers1

2

Try with this code

$sql="SELECT * FROM users";
$sql_query=mysql_query($sql);
$cur_date=date('Y-m-d H:i:s');

while($data=mysql_fetch_array($sql_query))
{

$lastDate=date("Y-m-d",strtotime($data['last_login_time']));
$currentDate = date("Y-m-d");

$dateDiff = abs(strtotime($currentDate) - strtotime($lastDate));

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

echo $years.'-'.$months.'-'.$days;

}
Nikul
  • 1,025
  • 1
  • 13
  • 33