0

I have a mysql datetime object, let's call it "purchase date", like so 2014-04-15 14:47:39. I also have a mysql time object, let's call it "shelf life", like so 168:00:00, meaning that product has a shelf life of 168 hours, or seven days, after its purchase date. I would like to know how many days there are until this product expires, with the following formula (or something similar)

daysRemainingBeforeExpiring = [purchase_date (datetime) + shelf_life (time)] - now(datetime)

Please correct me if my formula is wrong, but I believe this should return the number of days before this item expires (or a negative number if it's expired). How can I perform this math operation on the datetime and time objects in PHP?

3
  • Show us what you've tried so far Commented Apr 29, 2014 at 15:22
  • Perhaps that i will say a mistake but the best way to compare date in PHP is to use timestamp, it's really more easy for compare some date. fr2.php.net/manual/en/function.time.php Commented Apr 29, 2014 at 15:24
  • I disagree. DateTime is much better for date math. Commented Apr 29, 2014 at 15:25

1 Answer 1

1
$purchase_date = new DateTime('2014-04-15 14:47:39');
list($hours, $minutes, $seconds) = explode(':', '168:00:00');
$shelf_life    = new DateInterval("PT{$hours}H{$minutes}M{$seconds}S");
$expires_date  = $purchase_date->add($shelf_life); 
$now           = new DateTime();
$diff          = $now->diff($expires_date);
echo $diff->format('%r%d Days');

Demo

Sign up to request clarification or add additional context in comments.

1 Comment

perfect, thank you. the dateinterval was what I couldn't figure out properly

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.