Jeú Casulo Jeú Casulo - 1 year ago 70
PHP Question

Get the difference between two dates in every rows

I need to get the difference between 2 dates but not only between 2 specific dates, I am talking about a table that has the "pdt_expires" column, and I want to show how much days until this date, but in EVERY rows. Ex:

  • Rice - 2 lb - expires in 54 days

  • Beans - 3 lb - expires in 31 days

I saw THOUSAND of solutions for only 2 specific dates but none for this case. I wonder I would need:

  • a function in Product Model that access the "pdt_expire" and use Carbon to get the final value

- a function inside the View that get the $product->pdt_expire and get the final value

So any help would be great, thank you.

Answer Source

How about achieve it using just simple DATEDIFF query:

    \DB::raw('DATEDIFF(pdt_expires, NOW()) as expires_in')

So in every product you have, it will have an additional column called expires_in that stores different of days between NOW to pdt_expires.

DATEDIFF: How to get the number of days of difference between two dates on mysql?