qadenza
qadenza

Reputation: 9293

how to calculate difference in hours including current day

Column date is datetime format.
I need to display how much hours is remeining till a certain date.

$st = $db->query("select ev, date from event where ev = 'ng'");
$row = $st->fetch();
$d1 = new DateTime($row['date']);
$d2 = new DateTime();
$diff = $d1->diff($d2);
$diff = $diff->days * 24; // result: 2088

So this works, but hours of current day are not calculated. I tried:

$diff = $diff->hours;

and got the notice:

Undefined property: DateInterval::$hours

Any help?

Upvotes: 2

Views: 184

Answers (2)

parpar
parpar

Reputation: 339

Once you have the diff object, just format it so you can get the hours

$d1 = new DateTime($row['date']);
$d2 = new DateTime();
$diff = $d1->diff($d2);

to get the number of hours

echo ($diff->d * 24) + $diff->h

Upvotes: 1

Lawrence Cherone
Lawrence Cherone

Reputation: 46620

Because $diff->days returns the remaining days you can times that by 24 to get the hours, then you just add the remaining hours for the day on that, so essentially what your doing but just add the remaining hours for total hours

$st = $db->query("select ev, date from event where ev = 'ng'");
$row = $st->fetch();
$d1 = new DateTime($row['date']);
$d2 = new DateTime();
$diff = $d1->diff($d2);
// (days * 24) = hours + remaining hours
$hours = ($diff->days * 24) + $diff->h;

Example: 1 day 5 hours = 29 https://3v4l.org/KDS9r

Upvotes: 1

Related Questions