0

I am having a heck of a time trying to find the difference between two dates. I am getting a date out of a database and trying to compare it with the current date and time.

What I need is the number of hours between the two dates. If I format the date_diff as "%h%", I am only getting the subtracted hours between the hours, not the total time like between 2:00pm three days ago and 3:00pm today. With "%h" this only give me the result 1 hour.

With the code below, I am getting the error "Object of class DateInterval could not be converted to string" when trying to echo $SinceLastUpdate. I have tried all kinds of formatting of the dates and I am going nuts on this one.

Here is my current code:

//Database stuff
$SqLiteSqlStr = "SELECT Max(END_TIME) AS LAST_UPDATE FROM DATA_LOAD_LOG";   
PDO_Connect("sqlite:$SqLiteDB");
$results = PDO_FetchAll($SqLiteSqlStr);
foreach ($results as $row) { $DataUpdated = $row["LAST_UPDATE"];}

//Make some kind of attempt to find out how old the data is
$TodaysDate = new DateTime("now");
$SinceLastUpdate = date_diff(new DateTime($DataUpdated), $TodaysDate );
echo "<br>TodaysDate " . date_format($TodaysDate,"Y-m-d H:i:s");
echo "<br>DataUpdated " . $DataUpdated;
echo "<br>SinceLastUpdate " . $SinceLastUpdate; 

Right now, I don't care if the difference is in seconds, minutes or hours, I just need some kind of accurate number I can work with. What I am trying to do is check how old the data is. If it is more than three days old (72 hours), then I need to run my process to update the data.

Any help is going to be greatly appreciated.

Soren
  • 797
  • 5
  • 15
  • 32
  • Possible duplicate of [PHP find difference between two datetimes](https://stackoverflow.com/questions/15688775/php-find-difference-between-two-datetimes) – zod Jun 22 '17 at 21:35

1 Answers1

0

Your problem here is that you use just %h modifier.

Information in DateInterval stored not like total amount of hours between dates, but amounts of all types of date/time.

So, if you compare in your example

time like between 2:00pm three days ago and 3:00pm today

you get one hour with %h, yes. But you also get 3 days with %d modifier.

So, I suppose, you just need to check:

$days = $SinceLastUpdate->format('%d');
if ($days < 3) { /* do stuff */ }

But in more simple way you can just compare timestamps - current and $DataUpdated, if difference is greater than 3 days (3 * 86400) - do something:

$TodaysDate = new DateTime("now");
$du = new DateTime($DataUpdated);
if ($du->format('U') - $TodaysDate->format('U') > (86400 * 3)) {
    /* do stuff */
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64