Home > database >  How to calculate experience by using date with current date in laravel?
How to calculate experience by using date with current date in laravel?

Time:09-23

I am using laravel framework to develop api's , i have one column inside table with timestamp,i am fetching that value and i want to show that value to the 3 Years 2 Month or if it's been in days it should show 10days, i have tried by using carbon package to convert as per my requirement but i can't able to figure out can you please help me to achieve this one.

Ex1:-
$date = 2022-09-15 00:00:00;
//my expectation is **8days**
Ex2:-
$date = 2021-08-23 00:00:00;
//my expectation is 1 year 1 month

CodePudding user response:

Here is the example you can do like this

$Born = Carbon\Carbon::create(1986, 1,3);
$Age = $Born->diff(Carbon\Carbon::now())->format('%y Year, %m Months and 
%d Days');
echo $Age;

Here is your date example is working and it's result

$date1 = \Carbon\Carbon::create("2022-09-15 00:00:00");
$date2 = \Carbon\Carbon::create("2021-08-23 00:00:00");
$totalYearMonthDate = $date1->diff($date2)->format('%y Year, 
%m Months and %d Days');

Result:- 1 Year, 0 Months and 23 Days

CodePudding user response:

diffForHumans has parts and minimumUnit options that do what you want:

$options = [
    'parts' => 2,
    'minimumUnit' => 'day',
    'skip' => ['week'],
];
echo Carbon::parse('2022-09-15 00:00:00')->diffForHumans($options) . "\n";
echo Carbon::parse('2021-08-23 00:00:00')->diffForHumans($options) . "\n";

CodePudding user response:

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference ". $interval->y . " years, " . 
$interval->m." months, ".$interval->d." days "; 

Try doing like this

  • Related