Calculate age from the specified date in Carbon

Amit Merchant · April 15, 2022 ·

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.

The age property

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!

In Laravel

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.

$this->birthdate->age;

Pretty handy, no?

Learn the fundamentals of PHP 8 (and 8.1), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 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!

Comments?