我正在尝试获取生日为today, today + 1, today + 2
的记录。
假设某人出生于1991年6月16日。 我必须找到那些生日是今天,明天和后天的记录
$todayDate = date('Y-m-d');
$toDate1 = date('Y-m-d', strtotime($todayDate . ' + 1 days'));
$toDate2 = date('Y-m-d', strtotime($todayDate . ' + 2 days'));
我尝试使用orWhereDay, orWhereMonth
,但这没有任何意义。
编辑:我已经这样做了,但是我正在寻找一种更有效的方法。 https://pastebin.com/GRdRH2jC
答案 0 :(得分:0)
正确的代码似乎是
$date = new DateTime;
$date2 = $date->modify('+1 day');
$date3 = $date->modify('+2 day');
$formatted_date = $date->format('Y-m-d H:i:s');
$formatted_date2 = $date2->format('Y-m-d H:i:s');
$formatted_date3 = $date3->format('Y-m-d H:i:s');
修补程序输出
>>> $date = new DateTime;
=> DateTime @1558028326 {#3144
date: 2019-05-16 17:38:46.169709 UTC (+00:00),
}
>>> $date2 = $date->modify('+1 day');
=> DateTime @1558114726 {#3144
date: 2019-05-17 17:38:46.169709 UTC (+00:00),
}
>>> $date3 = $date->modify('+2 day');
=> DateTime @1558287526 {#3144
date: 2019-05-19 17:38:46.169709 UTC (+00:00),
}
>>> $formatted_date = $date->format('Y-m-d H:i:s');
=> "2019-05-19 17:38:46"
>>> $formatted_date2 = $date2->format('Y-m-d H:i:s');
=> "2019-05-19 17:38:46"
>>> $formatted_date3 = $date3->format('Y-m-d H:i:s');
=> "2019-05-19 17:38:46"
>>>
使用碳
>>> $today = Carbon\Carbon::now()
=> Carbon\Carbon @1558072952 {#3119
date: 2019-05-17 06:02:32.343195 UTC (+00:00),
}
>>> $date2 = $today->addDay();
=> Carbon\Carbon @1558159352 {#3119
date: 2019-05-18 06:02:32.343195 UTC (+00:00),
}
>>> $date3 = $today->addDays(2);
=> Carbon\Carbon @1558332152 {#3119
date: 2019-05-20 06:02:32.343195 UTC (+00:00),
}
>>>
答案 1 :(得分:-1)
您可以将Carbon类用于时间,使事情变得简单
Use Carbon/Carbon
$today = Carbon::now()->today();
$toDate1 = Carbon::now()->today()->addDays(1);
$todate2 = Carbon::now()->today()->addDays(2);
$todate2 = Carbon::now()->today()->addDays(3);
where('birthday, '>', $today)->where('birthday', '<', $toDate1); //today
where('birthday, '>', $toDate1)->where('birthday', '<', $toDate2); //today + 1
where('birthday, '>', $toDate2)->where('birthday', '<', $toDate3); //today + 2
如果您只想要一个月和一天,那么可以这样做
$today = Carbon::now()->today()->format('m-d');
答案 2 :(得分:-1)
$upcomingBdays = model::select('id', ... , 'birthday')->get()->filter(function ($model) {
// get the bday and change the year to this year so we can simply compare dates
$bday = Carbon::parse($model->birthday)->year(today()->year); // you can skip parsing if you have the field in the protected $dates on model
return $bday->between(today(), today()->addDays(2));
});
如果没有有关您要查询的模型的更多信息,这应该可以为您提供所需的信息。
确保您还将模型的生日字段添加到了
模型本身上的protected $dates [];
数组,因此Carbon
会自动对其进行解析。
答案 3 :(得分:-1)
您可以使用Carbon。示例:
User::whereBetween('birthday', [Carbon::today(), Carbon::today()->addDays(1)]);
如果要使用or,则需要将它们分组,如下所示:
User::where(function($query) {
$query->whereDate('birthday', Carbon::today())
->orWhereBetween('birthday', [Carbon::today(), Carbon::today()->addDays(1)])
->orWhereBetween('birthday', [Carbon::today(), Carbon::today()->addDays(2)])
})->get();