Wp3Dev
Wp3Dev

Reputation: 2079

Subtract datetime from current date time to get a timer

I have a column in a mysql databse that is expriation time of created post.... I have a page that is trying to show how many hours and seconds left until the time reaches the expiration time of each post. For instance I have this in my database:

2013-03-07 13:15:39

This shows when this post expires....

Now I want to be able to go to the page that displays each post and then show the amount of time left (based on the current time) until each posts expires.

2013-03-07 12:15:39

I have been using this so far:

$now = new DateTime(date("h:i:s",time()));
$exp = new DateTime($row['time_expires']);
$diff = $now->diff($exp);
printf('%d hours, %d minutes, %d seconds', $diff->h, $diff->i, $diff->s);

Where $row is fetching the post from the database

It has been working somewhat but seems to have issues sometimes... I have no clue why but it sometimes works great but then when I go check it again the time says 15 hours to expiration when it really should say 2 hours

Upvotes: 1

Views: 2880

Answers (1)

Wrikken
Wrikken

Reputation: 70540

h in date() is a 12-hour clock, which will create confusion, because DateTime will interpret it as a 24 hour one. A DateTime object will have the current time by default, so just use:

  $now = new DateTime();
  $exp = new DateTime($row['time_expires']);
  $diff = $now->diff($exp);

But Marc B's suggestion of doing it directly in the query is probably a better one.

Upvotes: 3

Related Questions