-1个月的PHP / Laravel日期/ strtotime显示当前月份

时间:2019-03-29 19:14:56

标签: php laravel

我遇到了一个问题,我试图在上个月的第一天和最后一天之间达到count(),并且它显示了当前月份。我已经有两个月的这段代码了,还没有看到这个问题。

今天是2019年3月29日。这是我在刀片服务器中要查询的内容:

{{date('F')}}                         // returns "March"
{{date('F', strtotime("-1 month"))}}  // returns "March"

// count scripts from last month
$first_day_last_month = date("Y-m-01", strtotime("-1 month"));
$last_day_last_month = date("Y-m-t", strtotime("-1 month"));
{{$doctor->scripts()->whereBetween('prescribe_date', [$first_day_last_month, $last_day_last_month])->count()}}

查询返回三月份的数据,而不是二月份的数据。这是对strtotime的滥用吗?

修改

在研究了重复的问题之后,我能够找出问题所在。 多亏了已接受的答案,我得以使用Carbon改进我的代码,并通过subMonthsNoOverflow(1)使用首选的Eloquent语法。

1 个答案:

答案 0 :(得分:1)

如果您使用Laravel,为什么不使用Carbon就这么简单:

Carbon\Carbon::now()->startOfMonth()->subMonth()->format('F');

-已编辑为使用subMonth,如@RossWilson所述。

相关问题