Calculate age from the specified date in Carbon — Amit Merchant — A blog on PHP, JavaScript, and more


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 CarbonCarbon;

// 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 do not 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.

Pretty handy, no?



Please enter your comment!
Please enter your name here