从当前日期中减去天数的 Laravel Carbon

138

我想从模型 "Users" 中提取那些 created_at 日期距离今天已经超过30天的对象。

Carbon::now() ==> 我需要的是 ==> Carbon::now() - 30天

$users = Users::where('status_id', 'active')
               ->where( 'created_at', '<', Carbon::now())
               ->get();

如何实现这个目标?

4个回答

293

使用subDays()方法:

$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::now()->subDays(30))
           ->get();

3
你确定要将“<”更改为“>”,以获取创建时间超过30天的用户吗? - Chris Forrence
2
我的条件是当前日期距离今天超过30天。我想这个逻辑会为我完成任务。 - cosmoloc
3
@AlexeyMezenin,原始提问者想要的是:以今天(12月13日)为例,“比今天早30天以上”的用户是指在11月13日之前创建的用户。请转达此意。 - Chris Forrence
需要注意的是,你应该将 H M S 重置为 00:00:00,否则你会得到相对于时间戳/日期时间字段的时间差。因此,可以添加 ->endOfDay()->hour(0)->minute(0)->second(0),或在日期设置中使用 date('Y-m-d 00:00:00') - tristanbailey
你确定不是 '<' 吗? - Damilare Koiki
显示剩余4条评论

17
从Laravel 5.6版本开始,您可以使用whereDate函数:
$users = Users::where('status_id', 'active')
       ->whereDate( 'created_at', '>', now()->subDays(30))
       ->get();

你还可以使用 whereMonth / whereDay / whereYear / whereTime


我喜欢这个,因为它使用了now()助手。 - Luciano Fantuzzi

9
您可以始终使用strtotime从当前日期中减去天数:
$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
           ->get();

4
可以将它改为 date('Y-m-d 00:00:00', strtotime("-30 天")),使其更加简洁。 - tristanbailey

1
与strtotime或DateTime一样,任何(相对)日期表达式也可以与carbon::parse一起使用。
$users = Users::where('status_id', 'active')
           ->where( 'created_at', '>', Carbon::parse('Now -30 days'))
           ->get();

另外,对于“现在-30天”,也可以使用表达式“-30days”或“-720小时”。

“现在-30天”考虑了当前时间。如果您需要00:00的时间,请使用“今天-30天”。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接