首页 > 解决方案 > Laravel Carbon::today() 方法返回前一天

问题描述

我编写了一个函数来根据日期过滤用户和代理预订的票。这基本上是一个订票应用程序。在此用户和代理可以预订不同的票,因此在管理仪表板中,我将显示用户今天预订的票总数,反之亦然。因此,我使用 Carbon 来验证今天的日期。但我得到了不同类型的输出!

控制器 :

$ticketsTodayUsers = Booking::with('users')->where("createdAt", ">=", Carbon::today())->whereHas("users", function($subQuery){ 
    $subQuery->where("usertype", "=", "normal");
    })->get();

所以在这里我有两个表,booking 和 user 表,我通过它验证今天使用 carbon::today() 创建的票,用户类型为普通或代理。

但是当我今天(2018 年 9 月 19 日)检查时,我得到了昨天(2018 年 9 月 18 日)的计数结果。我没有得到今天的计数,它是零,而是计数来自昨天或很久以前,如 2018 年 9 月 14 日。我不知道我在哪里做错了!

主要条件是我需要将每天的用户和代理预订计数分开,因此通过使用从 db 和 carbon today 函数提交的 createdAt ,我试图匹配两者。但我没有得到预期的答案!

标签: phplaravellaravel-5php-carbon

解决方案


尝试使用 $tz 参数 - TimeZone。

Carbon::today('Asia/Calcutta');

并尝试使用WhereData()WhereDay()

->whereDay('createdAt', '=', date('d'))

或者

->whereDate('createdAt', Carbon::today())

当然有适当的时区

Booking::with('users')->whereDate('createdAt', Carbon::today('Asia/Calcutta')->toDateString())->whereHas("users", function($subQuery){
            $subQuery->where("usertype", "=", "normal");
        })->get();

推荐阅读