Laravel Carbon, retrieve today's date with weekday?

青春壹個敷衍的年華 提交于 2020-03-13 07:18:11

问题


I am using carbon to compare 2 dates with today's date, however I also have another field in a database called weekday which contains values like:

'MO' 'TU' 'WE'

So I don't only want to search and output by dates but also search by a weekday so:

public function show($id)
{   
    $today = Carbon::now();
    $weekday = //whatever carbon or something else has to retrieve today's day
    $event = Event::with('businesses')
       ->where('startdate', '<', $today->format('Y-m-d'))
       ->where('endate', '>', $today->format('Y-m-d'))
       //or where ('weekday') = $weekday?
       ->get();
    return view('events.showEvent', compact('event'));
}

回答1:


I'm not sure that Carbon has such formatting, but what you could do is get the wekkday from a map of days and the current week day constant:

$weekMap = [
    0 => 'SU',
    1 => 'MO',
    2 => 'TU',
    3 => 'WE',
    4 => 'TH',
    5 => 'FR',
    6 => 'SA',
];
$dayOfTheWeek = Carbon::now()->dayOfWeek;
$weekday = $weekMap[$dayOfTheWeek];



回答2:


If you're in an English-speaking locale, you can get that short weekday format by doing some processing on Carbon's l format, which returns weekday names:

strtoupper(substr($today->format('l'), 0, 2)); // Returns 'MO', 'TU', etc

It can be even shorter if you have access to Carbon 2 (available on 2018-08-31):

strtoupper($today->isoFormat('dd'));


来源:https://stackoverflow.com/questions/44923829/laravel-carbon-retrieve-todays-date-with-weekday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!