Search code examples
laraveldatelaravel-5php-carbon

Check if any date is older than 5 years


I am trying to figure out the best way to achieve something. I am looping through some data that involves a group of dates

foreach ($fields['dates'] as $key => $dates) {
    $fields['dates'][$key]['datestring'] = Carbon::createFromFormat(
        'dmY',
        $dates['datestring']
    );
    var_dump($fields['dates'][$key]['datestring']);
}

The var_dump above produces something like the following

object(Carbon\Carbon)#330 (3) { ["date"]=> string(26) "2019-08-08 12:41:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" } object(Carbon\Carbon)#328 (3) { ["date"]=> string(26) "1987-08-08 12:41:00.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(3) "UTC" }

So above this, I have created a variable to identify whether at least one of the dates is more than 5 years ago. I have also created a date object for today.

$moreThanFiveYears = false;
$now = Carbon::now();

Now what I am trying to figure out is how I perform the actual check? When I try the above, it complains because $now is not the same format as my other dates. I have tried adding a format to it, but it produces only something like 20190219 and not the additional data the original dates produce.

So how can I loop all my dates to ensure at least one is greater than 5 years?

Thanks


Solution

  • get five years ago by subYears() and compare them by greaterThan().

    $fiveYearsAgo = Carbon::now()->subYears(5);
    
    foreach ($fields['dates'] as $key => $dates) {
        $fields['dates'][$key]['datestring'] = Carbon::createFromFormat(
            'dmY',
            $dates['datestring']
        );
    
        if ($fields['dates'][$key]['datestring']->greaterThan($fiveYearsAgo)) {
            $moreThanFiveYears = false;
        }
    }