You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从数据库读取日期计算与当前日期间隔天数报错求助

问题根源分析

你遇到的错误核心原因是:get()方法返回的是Eloquent集合对象(本质是包含多个模型实例的数组),而不是单个日期字符串。当你直接把这个集合传给Carbon构造函数时,PHP会自动把集合转成JSON格式的字符串(也就是报错里的[{"quit_date":null},{"quit_date":null}]),这种格式完全不符合日期解析规则,自然会触发DateTime解析失败的错误。

而手动设置$quit_date为"2019-04-25 00:00:00.000000"时,你传入的是合法的日期字符串,所以Carbon能正常解析。

解决方案

根据你的业务场景,分两种情况处理:

场景1:每个用户仅对应一条quit_date记录

如果你的user_id是唯一关联(每个用户只有一条Information记录),用first()替代get()获取单条记录,再提取日期字段:

// 获取当前用户的单条信息记录
$infoRecord = Information::select('quit_date')
    ->where('user_id', '=', \Auth::user()->id)
    ->first();

// 先判断记录存在且quit_date不为null,避免后续报错
if ($infoRecord && $infoRecord->quit_date) {
    $date = Carbon::parse($infoRecord->quit_date);
    $now = Carbon::now();
    $day = $date->diffInDays($now);
} else {
    // 处理无记录或日期为空的情况,比如设为0或其他默认值
    $day = 0;
}

场景2:每个用户对应多条quit_date记录

如果一个用户有多个quit_date记录,需要遍历集合逐个处理:

// 获取当前用户的所有quit_date记录
$quitDateRecords = Information::select('quit_date')
    ->where('user_id', '=', \Auth::user()->id)
    ->get();

$dayIntervals = [];
foreach ($quitDateRecords as $record) {
    if ($record->quit_date) {
        $date = Carbon::parse($record->quit_date);
        $now = Carbon::now();
        $dayIntervals[] = $date->diffInDays($now);
    } else {
        // 对null日期的处理,比如存入null或0
        $dayIntervals[] = null;
    }
}
// $dayIntervals数组中存储了每个日期对应的间隔天数
额外提醒
  • 务必处理quit_date为null的情况,否则即使拿到单个字段值,Carbon解析null也会报错。
  • 如果你确定字段是日期类型,Laravel会自动将其转为Carbon实例,所以也可以直接使用:
    // 前提是你的Information模型中已将quit_date加入$dates属性或用了日期类型转换
    $date = $infoRecord->quit_date;
    $day = $date->diffInDays(Carbon::now());
    

内容的提问来源于stack exchange,提问作者Aizu Zuyyin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:32:19