日期比较在Laravel(PHP)中不起作用

我无法比较两个日期。

我要完成的任务:

我在laravel中有一个简单的中间件,在其中我检查一个日期是否高于另一个日期。

代码(Middleware \ ifTrialExpired.php):

$subscription = Auth::user()->subscription;
$date = Carbon::now()->isoFormat('DD-MM-YY');

if($date > $subscription->trial_period_end && $subscription->has_trial)
{
    return redirect()->route('settings.plan.index');
} else {
    return $next($request);
}

问题出在哪里:

在这种情况下,我数据库中的“ trial_period_end”日期为“ 05-12-19”,当前日期为“ 06-11-19”。但是我一直将我重定向到“ settings.plan.index”路由,但是我只希望在当前日期(06-11-19)大于trial_period_end(05-12-19)时发生。

有人知道如何解决此问题吗?

yesonghui 回答:日期比较在Laravel(PHP)中不起作用

比较日期

声明两个日期

$date1 = "12-03-26"; 
$date2 = "2011-10-24"; 

使用strtotime()函数将日期转换为dateTimestamp

$dateTimestamp1 = strtotime($date1); 
$dateTimestamp2 = strtotime($date2); 

比较时间戳记日期

if ($dateTimestamp1 > $dateTimestamp2) 
    echo "$date1 is latest than $date2"; 
else
    echo "$date1 is older than $date2"; 
,

您可以尝试使用碳gt函数进行日期比较。:https://carbon.nesbot.com/docs/#api-comparison

尝试以下代码:

$subscription = Auth::user()->subscription;
$date = Carbon::now();

$sub_date  = Carbon::create($subscription->trial_period_end);   

if($date->gt($sub_date) && $subscription->has_trial)
{
    return redirect()->route('settings.plan.index');
} else {
    return $next($request);
}
,

如果您将日期时间作为字符串进行比较,则应该始终使用YYYY-MM-DD格式作为日期,因为任何其他格式都将无法作为字符串比较。

但是,更好的是,根本不使用字符串比较。

Carbon类包含比较方法,因此将所有内容都制成Carbon对象,然后使用它们进行比较。

类似这样的事情应该可以解决:

$subscription = Auth::user()->subscription;
$dateNow = Carbon::now();

$trialEndDate = Carbon::createFromFormat('d-m-Y',$subscription->trial_period_end);

if($dateNow->gt($trialEndDate) && $subscription->has_trial)
{
    return redirect()->route('settings.plan.index');
} else {
    return $next($request);
}

(注意:这是未经测试的,可能需要调整,因为我实际上不知道您的trial_period_end是以什么格式存储的。)

,

尝试一下

 $date1 = "12-03-26"; 
 $date2 = "20-10-24"; 
 $dateTimestamp1 = date('d-m-Y',strtotime($date1)); 
 $dateTimestamp2 = date('d-m-Y',strtotime($date2));  
 if ($dateTimestamp1 > $dateTimestamp2) 
 echo "$date1 is latest than $date2"; 
 else
 echo "$date1 is older than $date2"; 

输出将为

 12-03-26 is latest than 20-10-24
本文链接:https://www.f2er.com/3153434.html

大家都在问