Calculate age from the specified date in Carbon
When you’re working with dates in Laravel, chances are high that you might have done it with this library called Carbon.
Carbon is a great library that makes working with dates a breeze and Laravel provides support for it out-of-the-box.
So, there are many great things that you can do with Carbon but recently, I got to know about this nice little functionality that can make your life easier in certain scenarios.
Essentially, let’s say you have a date and you want to calculate the age from this date, it’s pretty easy to do so with Carbon.
Here’s how you can do it.
use Carbon\Carbon; Carbon::parse('2001-01-01')->age; // 21
As you can tell, you just need to call the
age property on the Carbon instance which calculates the age from that date for you. You don’t need to do complex calculations yourself!
This is useful in a case where you need to calculate the age of the users of your Laravel application using a field, let’s say,
birthdate. In such scenarios, here’s how you can do it.
Pretty handy, no?
👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!