Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Crazylife's avatar

Calculation for stock expiry date

Check Product A expiry date:

$manufacture_date = "2018-10-21";
$shelf_life =  7;
$expiry_date = Carbon::parse($manufacture_date)->addDays(($shelf_life - 1))->format('Y-m-d'); // 2018-10-27

Here i calculate the difference between expiry date and today date.

// expiry date - today date
$today = strtotime(Carbon::now()->format('Y-m-d'));
$expiry = strtotime(expiry_date);
$diff_day = (int)floor(($expiry-$today)/(60*60*24));

if day difference less than zero meaning all considered as expired. Am i doing in correct way for calculation?

0 likes
5 replies
Vilfago's avatar

It should work, but I think you could do thing faster using Carbon API.

And if you don't print/echo the date, don't waste time formating it.

$manufacture_date = "2018-10-21";
$shelf_life =  7;
$expiry_date = Carbon::parse($manufacture_date)->addDays(($shelf_life - 1));


$diff_day = Carbon::now()->diffInDays($expiry_date);
Crazylife's avatar

@Vilfago Yes, but this will return positive all the time, i want to detect whether it is expired or not instead of just different of day.

Vilfago's avatar

You're right, sorry. It's missing the 2nd argument

$manufacture_date = "2018-10-21";
$shelf_life =  7;
$expiry_date = Carbon::parse($manufacture_date)->addDays(($shelf_life - 1));


$diff_day = Carbon::now()->diffInDays($expiry_date, false);
Crazylife's avatar

@Vilfago if using your way, i think need to add some other calculation to get the difference day, am i right? When manufacture_date = 2018-10-21, shelf life = 7 then my expiry date will be 2018-10-27. If today date 2018-10-25, follow your method it will return 1 day. By right, the difference should be 2 days? Correct me if i am wrong.

Vilfago's avatar

It should be 2 days, but you can try it... and if not, you can just add +1.

But as your code is working, if you think it's better, just go with it. I just suggest you something else, but you don't have to use it :)

Please or to participate in this conversation.