Laravel Carbon 查看日期是否过去

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47059484/
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-14 16:53:49  来源:igfitidea点击:

Laravel Carbon See if date is in the past

phplaravelphp-carbon

提问by Packy

I am very confused by this, maybe its something simple I am not seeing. If I want to see if a date is in the past of today I should be able to do something like this?

我对此感到非常困惑,也许是我没有看到的一些简单的东西。如果我想查看日期是否在今天的过去,我应该能够做这样的事情吗?

if( $league->date_start <= Carbon::now() ){
    $join  = false;
    $message = 'Sorry, the league has already started';
}

if I dump out the dates its

如果我丢弃日期

$league->date_start = 2017-07-31 00:00:00
Carbon::now() = 2017-11-01 16:29:27

$league->date_startis a protected date so its a carbon instance

$league->date_start是一个受保护的日期,所以它是一个碳实例

But this doesnt work, if I switch it to $league->date_start >= Carbon::now()it works and wont let me join. I know the "league" start date is in the past so shouldnt it be $league->date_start <= Carbon::now()?????

但这不起作用,如果我切换到$league->date_start >= Carbon::now()它,它会起作用并且不会让我加入。我知道“联赛”的开始日期是过去的,所以不应该是$league->date_start <= Carbon::now()?????

回答by Marcin Nabia?ek

There's built-in Carbon method isPastso you can use:

有内置的 Carbon 方法,isPast因此您可以使用:

$league->date_start->isPast()

to determine if date is in past or not

确定日期是否过去

回答by Ivan Kalita

Check the section “Comparison” on carbon docs. You should call $first->lte($second)to compare two carbon instances.

检查carbon docs上的“比较”部分。您应该打电话$first->lte($second)来比较两个碳实例。

回答by SagunKho

Try using if ($league->date_start->diffInSeconds() >= 0). The method diffInSecondsreturns the difference between the current time and your carbon instance.

尝试使用if ($league->date_start->diffInSeconds() >= 0). 该方法diffInSeconds返回当前时间和您的 carbon 实例之间的差异。

Here's an example of an output from tinker -

这是 tinker 输出的示例 -

>>> $now = \Carbon\Carbon::now();
=> Carbon\Carbon {#648
     +"date": "2017-11-01 16:41:04.000000",
     +"timezone_type": 3,
     +"timezone": "UTC",
   }
>>> $now->diffInSeconds();
=> 5
>>> $now->diffInSeconds();
=> 7
>>> $now->diffInSeconds();
=> 8
>>> $now->diffInSeconds();
=> 10
>>> $now->diffInSeconds() > 0
=> true