Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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.

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 (including 8.1, 8.2, and 8.3), 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-digest 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.

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?