1

I wish to compare two dates - $dateX (datetime in past) with $currentDatetime (current datetime). For instance: check if $dateX was 7 days ago or not. All should happen in Laravel Blade Engine view by using Carbon.

Can you give some example? Thanks!

Machavity
  • 30,841
  • 27
  • 92
  • 100
Adam Kozlowski
  • 5,606
  • 2
  • 32
  • 51

4 Answers4

3

This think can be achieved easily with Carbon, so i'm supposing that both $dateX and $currentDateTime are Carbon instances, accordingly if you wanna check time diff in days simply use diffInDays

for example

if( $currentDateTime->diffInDays( $dateX ) > 7 ){
    // do sonething here
}

in the end i really wanna say that carbon docs are very clear and easy to read

  • In fact,if i want to use it in blade it should look like: {{ Carbon\Carbon::today()->diffInDays(Carbon\Carbon::parse($dateX)) }} – Adam Kozlowski Dec 17 '17 at 09:37
1

First get these date times into carbon instances.

@if ($dateX->diffInDays($currentDateTime, false) == 7)
    ...
@endif

Carbon Docs - Difference

lagbox
  • 48,571
  • 8
  • 72
  • 83
1

If you want to know if the date is earlier than a week ago, you could do this:

@if ($dateX < now()->subWeek())

The diffInDays() will work too, but only if all $dateX days are in the past and always will be. The code above is more explicit. Also, what if you'll need to change the logic?

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • `diffInDays` take a second argument, for absolute, set it to false and it will return a negative number in that case, which would not equal 7. – lagbox Dec 14 '17 at 20:14
0

You can check this with diff. Also check if a date is set before the other.

$date1 = \Carbon\Carbon::create(2017, 10, 10);
$date2 = \Carbon\Carbon::create(2017, 10, 20);

$difference = $date1->diff($date2)->days;
$before = $date1 < $date2;

if (before && $difference < 7) {
    //Date 1 more than 7 days before date 2            
}
Laerte
  • 7,013
  • 3
  • 32
  • 50