【问题标题】:Laravel Carbon subtract days from current dateLaravel Carbon 从当前日期减去天数
【发布时间】:2017-04-28 13:59:19
【问题描述】:

我正在尝试从模型“用户”中提取对象,其 created_at 日期已超过 从今天起 30 天

Carbon::now() ==> 我想要 ==> Carbon::now() - 30 天

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

如何做到这一点?

【问题讨论】:

    标签: php laravel datetime php-carbon


    【解决方案1】:

    使用subDays()方法:

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

    【讨论】:

    • 您确定将“”以获取 30 天前创建的用户吗?
    • 我的条件是当前日期距当前日期超过 30 天。我想这个逻辑为我完成了任务
    • 很高兴它有帮助。 ) @ChrisForrence 是的,如果我使用&lt;,它将返回在now minus 30 days 点之前创建的所有用户。
    • @AlexeyMezenin 这就是原始提问者正在寻找的;以今天(12 月 13 日)为例,“从今天起超过 30 天”将是在 11 月 13 日之前创建的用户。
    • 我猜他的more 在这里是指laterCarbon::now() ==&gt; I want as ==&gt; Carbon::now() - 30days 也很好地解释了 OP 想要什么。
    【解决方案2】:

    您始终可以使用strtotime 减去从当前日期算起的天数:

    $users = Users::where('status_id', 'active')
               ->where( 'created_at', '>', date('Y-m-d', strtotime("-30 days"))
               ->get();
    

    【讨论】:

    • 可以让date('Y-m-d 00:00:00', strtotime("-30 days")更整洁
    【解决方案3】:

    从 Laravel 5.6 你可以使用whereDate:

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

    你还有 whereMonth / whereDay / whereYear / whereTime

    【讨论】:

    • 我喜欢这个,因为它使用了 now() 助手。
    猜你喜欢
    • 1970-01-01
    • 2012-04-29
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    相关资源
    最近更新 更多