将数据库的时间戳与过去6个月进行比较

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';
}

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.

You can use Carbon to compare:

if $d is an instance of a model, created_at should be already a carbon object

$deadline = Carbon::now()->subMonths(6);

if($d->created_at.gt($deadline)){  
    // Do something 
    // Set the format here
}   

Carbon has multiple comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals