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

webfuelcode's avatar

Trying to calculate age in livewire

There is laravel tutorial on age calculating or a date calculator. I am trying to do the same in livewire.

$newdate = date_create('15-02-2023');
$interval = Carbon::parse($newdate)->age;

Above is what I found. I just wanna make the result with livewire because I am already using livewire in my project. What is the way to do it in livewire?

0 likes
4 replies
vincent15000's avatar

It's exactly the same way in Laravel than in Livewire : in both cases, it's only PHP code.

1 like
webfuelcode's avatar

@vincent15000 Thanks, I just tried again and it worked but the result is not correct. stackoverflow posts do work but the result shows the wrong and does not even change.

$date = '2023-01-20';
$cal = Carbon::parse($date)->diff(Carbon::now())->format('%y years, %m months, %d days);

Shows 53 years, 1 month, 20 days And even changing the date, shows the same result.

Second try, on two different dates (calculating the years between two days) I got the error diffInYears on int

$this->newdate = $this->date-$this->month-$this->year;
$this->to = Carbon::parse('2022-02-20');
$this->interval = $this->newdate->diffInYears(Carbon::parse($this->to));
1 like
Snapey's avatar
Snapey
Best Answer
Level 122

@webfuelcode this is not a livewire issue, you just need to understand how Carbon and date objects work

for instance, carbon objects are mutable, which means this;

$this->newdate = $this->date-$this->month-$this->year;

gets the date object and tries to subtract whatever is in month and year, and then save to newdate, however, $this->date gets modified in the process so $this->date and $this->newdate end up identical

Your diff attempt, you already have a carbon object so no need to parse it again

$this->interval = $this->newdate->diffInYears($this->to);
1 like
newbie360's avatar

This line is calculation by -, not an object

$this->newdate = $this->date - $this->month - $this->year;

thats why you got an error

got the error diffInYears on int

where the $this->date , $this->month , $this->year come from

1 like

Please or to participate in this conversation.