VinoCoder
VinoCoder

Reputation: 1153

calculate how many years and months between two month and year in laravel

I want to calculate the difference between two month and year. My input for calculating month and year is

$fromYear = 2016;
$fromMonth = 3;
$toYear = 2018;
$toMonth = 9;

And i want a output like 2 years, 6 months or 2.5 years. Im using laravel for develope my application. I want to achieve this through carbon or default php function. Kindly help me in this.

Upvotes: 0

Views: 2530

Answers (3)

Jimmy Martinez
Jimmy Martinez

Reputation: 44

You can also try with Carbon it can help you with date validation as well.

$fromYear = 2016;
$fromMonth = 3;
$toYear = 2018;
$toMonth = 9;

$from = Carbon::parse($fromYear.'-'.$fromMonth);
$to = Carbon::parse($toYear.'-'.$toMonth);
$diff = $from->diffForHumans($to, true, false, 6);

"2 years 6 months"

Upvotes: 0

Munteanu Petrisor
Munteanu Petrisor

Reputation: 491

Make 2 carbon instances like that

$year = 2000; $month = 4; $day = 19
$hour = 20; $minute = 30; $second = 15; $tz = 'Europe/Madrid';
$date = Carbon::createFromDate($year, $month, $day, $tz);
$date->diffForHumans($secondDate);

Upvotes: 3

Sougata Bose
Sougata Bose

Reputation: 31749

This should help -

$fromYear = 2016;
$fromMonth = 3;
$toYear = 2018;
$toMonth = 9;

$datetime1 = date_create($fromYear . '-' . $fromMonth . '-01');// Concatenate & consider date starts from 1st
$datetime2 = date_create($toYear . '-' . $toMonth . '-01');

$interval = date_diff($datetime1, $datetime2);

var_dump($interval->y . ' years, ' . $interval->m . ' months');

Code

O/P

string(17) "2 years, 6 months"

Need to add proper checks if required.

Upvotes: 1

Related Questions