Search code examples
phplaravelphp-carbon

Comparing timestamp from database to last 6 months


I'm using laravel and for some reason my logic here isn't applying correctly.

The if statement here should take the results from the database and see if the created_at timestamp is within the last 6 months. If so, I have a css class for 'newCust' below. If the created_at timestamp is past 6 months, it should not be applied.

I'm using subMonth to get the last 6 months but it seems like it's not applying because now it's applying the CSS class to all rows so I'm wondering if my date comparison is off here.

$d->createdAt = new \DateTime($d->created_at);  // created_at is full timestamp (2011-01-01 00:00:00)
$deadline = Carbon::now()->subMonths(6)->format('Y-m-d H:i:s');
if($d->createdAt > $deadline){  // I'm trying to say here that if the created_at timestamp is within the last 6 months, then apply following logic
$d->call_status = 'newCust';
}

Solution

  • Using just plain old DateTime this will do what you want

    $createdAt = new \DateTime('2017-11-17 00:00:00');
    echo $createdAt->format('d/m/Y H:i:s') . PHP_EOL;
    
    $deadline = new \DateTime();
    $deadline->sub( new DateInterval('P6M') );
    echo $deadline->format('d/m/Y H:i:s') . PHP_EOL;
    
    if ($createdAt > $deadline) {
        echo 'YES';
    }else{
        echo 'NO';
    }
    

    Adjust the date used by $createdAt to test it.