Laravel Carbon,用工作日检索今天的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44923829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 17:46:59  来源:igfitidea点击:

Laravel Carbon, retrieve today's date with weekday?

laraveldatetimelaravel-5php-carbon

提问by Przemek Wojtas

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:

我正在使用 carbon 将 2 个日期与今天的日期进行比较,但是我在一个名为 weekday 的数据库中还有另一个字段,其中包含如下值:

'MO' 'TU' 'WE'

'MO' 'TU' '我们'

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'));
}

回答by thefallen

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:

我不确定 Carbon 是否具有这样的格式,但是您可以做的是从天和当前工作日常量的地图中获取 wekkday:

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

回答by leonardost

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

如果您在讲英语的语言环境中,您可以通过对 Carbon 的l格式进行一些处理来获得简短的工作日格式,该格式返回工作日名称:

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):

如果您可以访问 Carbon 2(可在 2018-08-31 上获得),它甚至可以更短:

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