2

I need to compare two dates and find which date is greater.

 $actual_date = Carbon::createFromFormat('d-m-Y',$night_out->actual_return_date);
 $expected_date =  Carbon::createFromFormat('d-m-Y', $night_out->expected_return_date);

 $days = $expected_date->diffInDays($actual_date);  // gives the days count only

Thanks in Advance!

Neha
  • 2,136
  • 5
  • 21
  • 50
  • Does this answer your question? [How can I compare two dates in PHP?](https://stackoverflow.com/questions/3847736/how-can-i-compare-two-dates-in-php) – nageen nayak Nov 14 '19 at 06:35

3 Answers3

4

Carbon is an extension of datetime and inherits all properties of the base class. DateTime objects and thus carbon objects are directly comparable. Special comparison methods are not needed for this case.

if($actual_date > $expected_date){
     // do something
}

If only the date which is greater is needed, you can do that

$max_date = max($actual_date , $expected_date);

Note: $ max_date is an object reference of $actual_date or $expected_date. You can get a copy with the copy () method or use clone.

$max_date = max($actual_date , $expected_date)->copy();
jspit
  • 7,276
  • 1
  • 9
  • 17
3

You can use carbon method greaterThan()

if($actual_date->greaterThan($expected_date)){
     // logic here
 }
Poldo
  • 1,924
  • 1
  • 11
  • 27
0

Use gt function for that:

$actual_date = Carbon::createFromFormat('d-m-Y',$night_out->actual_return_date);
$expected_date =  Carbon::createFromFormat('d-m-Y', $night_out->expected_return_date);

if($expected_date->gt($actual_date)){            
    return $expected_date; //Max date
} else {
    return $actual_date;  //Min date
}

OR:

You need to find a greater date from two dates using max and array_map function like:

$actual_date = Carbon::createFromFormat('d-m-Y',$night_out->actual_return_date);
$expected_date =  Carbon::createFromFormat('d-m-Y', $night_out->expected_return_date);

// store dates value into an array to find the max date.

$date = array();
$date['actual_date'] = $actual_date;
$date['expected_date'] = $expected_date;

$max = max(array_map('strtotime', $date));

echo date('d-m-Y', $max);
Amit Senjaliya
  • 2,867
  • 1
  • 10
  • 24