Reputation: 60
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
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
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
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