Laravel Carbon See if date is in the past

假如想象 提交于 2019-11-28 03:30:15

问题


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_start is a protected date so its a carbon instance

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()?????


回答1:


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

$league->date_start->isPast()

to determine if date is in past or not




回答2:


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




回答3:


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

Here's an example of an output from 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


来源:https://stackoverflow.com/questions/47059484/laravel-carbon-see-if-date-is-in-the-past

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