ipi bk
ipi bk

Reputation: 60

calculate years beetwen two dates laravel

i have mySQL database table field :

description
unit
start_date
end_date

for example :

start_date : 05-07-2019

end_date : 10-08-2021

how I calculate number of years?

Upvotes: 0

Views: 1651

Answers (3)

Jithesh Jose
Jithesh Jose

Reputation: 1814

Try

 $datetime1 = new DateTime("05-07-2019");
 $datetime2 = new DateTime("10-08-2021");
 $difference = $datetime1->diff($datetime2);
 echo 'Difference: '.$difference->y.' years, ' 
               .$difference->m.' months, ' 
               .$difference->d.' days';

Output will be

Difference: 2 years, 1 months, 5 days

Hope this helps :)

Upvotes: 1

Maulik Shah
Maulik Shah

Reputation: 1050

Try this with carbon,

use Carbon\Carbon;


$startDate = Carbon::parse('05-07-2019'); 
$endDate = Carbon::parse('10-08-2021'); 
$diff = $startDate->diffInYears($endDate);

Hope this helps :)

Upvotes: 4

HVD
HVD

Reputation: 251

Try to use date_diff, in your example its will return 1.

$start_date = date_create("05-07-2019");
$end_date = date_create("10-08-2021");
$diff = date_diff($start_date, $end_date);
echo $diff->y;

Upvotes: 0

Related Questions