Laravel/PHP日期时间比较问题咨询:如何对比时间与当前日期
嘿,我来帮你捋清楚Laravel/PHP里的时间对比问题!你已经写了基础的日期和小时获取代码,接下来咱们分场景一步步实现对比逻辑~
一、指定日期与当前日期的对比
你已经把当前日期和请求来的日期都转成了Y-m-d格式,这个格式非常适合直接做字符串对比,因为它是按年→月→日的顺序排列的,字符串比较的结果和时间逻辑完全一致:
$now_time = date('H'); $current_day = date('Y-m-d'); $that_date = date('Y-m-d', strtotime($request->date)); // 判断指定日期是否等于今天 if ($that_date === $current_day) { echo "指定日期就是今天"; } // 判断指定日期是否在今天之前 if ($that_date < $current_day) { echo "指定日期早于今天"; } // 判断指定日期是否在今天之后 if ($that_date > $current_day) { echo "指定日期晚于今天"; }
如果你用的是Laravel,更推荐用框架自带的Carbon扩展包来处理时间,它的语法更直观,还能避免很多格式兼容问题:
use Carbon\Carbon; $current_day = Carbon::today(); // 今天的00:00:00 $that_date = Carbon::parse($request->date)->startOfDay(); // 将请求日期转为当天起始时间 // 相等判断 if ($that_date->eq($current_day)) { // 逻辑代码 } // 早于今天 if ($that_date->lt($current_day)) { // 逻辑代码 } // 晚于今天 if ($that_date->gt($current_day)) { // 逻辑代码 }
二、两个时间的对比
你已经获取了当前小时$now_time,如果要和另一个时间的小时对比,可以先把目标时间也转成小时格式,再转成整数比较:
// 假设请求里有个time字段,比如"14:30" $that_hour = (int)date('H', strtotime($request->time)); $now_hour = (int)$now_time; if ($that_hour > $now_hour) { echo "指定时间的小时晚于当前小时"; } elseif ($that_hour === $now_hour) { echo "指定时间和当前时间在同一小时"; } else { echo "指定时间的小时早于当前小时"; }
如果需要对比完整的时间(包含时分秒),同样可以用原生PHP字符串对比,或者Carbon的方法:
// 原生PHP写法 $current_full_time = date('Y-m-d H:i:s'); $that_full_time = date('Y-m-d H:i:s', strtotime($request->datetime)); if ($that_full_time > $current_full_time) { echo "指定时间在当前时间之后"; } // Carbon写法 $current_time = Carbon::now(); $that_time = Carbon::parse($request->datetime); if ($that_time->isAfter($current_time)) { echo "指定时间在当前时间之后"; } elseif ($that_time->isSameAs($current_time)) { echo "两个时间完全一致"; } elseif ($that_time->isBefore($current_time)) { echo "指定时间在当前时间之前"; }
小提醒
要注意strtotime($request->date)的解析成功率,建议先对请求的日期参数做格式验证,比如在Laravel里可以这么做:
$request->validate([ 'date' => 'required|date', // 确保是合法日期格式 // 如果是时间字段,用 'time' => 'required|date_format:H:i' 之类的规则 ]);
内容的提问来源于stack exchange,提问作者alpvel
相关产品推荐
相关产品推荐

