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

时间:2018-05-16 15:31:41

标签: php laravel php-carbon

我使用了laravel,由于某种原因,我的逻辑并没有正确应用。

此处的if语句应该从数据库中获取结果,并查看created_at时间戳是否在过去6个月内。如果是这样,我有一个css课程,用于' newCust'下面。如果created_at时间戳超过6个月,则不应该应用它。

我使用subMonth来获取最近6个月,但它似乎没有应用,因为现在它将CSS类应用于所有行,所以我想知道我是否日期比较在这里。

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

2 个答案:

答案 0 :(得分:2)

使用普通的旧DateTime,这将做你想要的事情

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

调整$createdAt使用的日期进行测试。

答案 1 :(得分:2)

您可以使用Carbon进行比较:

如果$d是模型的实例,created_at应该已经是碳对象

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

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

Carbon有多种比较功能:

  • eq()等于
  • ne()不等于
  • gt()大于
  • gte()大于或等于
  • lt()少于
  • lte()小于或等于
相关问题