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

Laravel 7 如何将数据库查询的日期格式转换为Unix时间戳

问题核心原因

你调用getTimestamp()不生效的核心原因是:pluck()方法返回的是集合(Collection)对象,不是单个时间字符串/DateTime对象,无法直接调用时间处理方法。

可用解决方法

方法1:直接查询单个字段值,用原生PHP转换

如果只需要单条记录的updated_at值,用value()方法直接取字段值更合适,再通过strtotime()直接转Unix时间戳:

// 直接获取单个updated_at字符串
$updatedAtStr = \DB::table('tickets')
        ->where('id', $ticket)
        ->value('updated_at');
// 转10位Unix时间戳
$timestamp = strtotime($updatedAtStr);

方法2:配合Carbon类处理(更适合后续时间计算)

Laravel自带Carbon日期处理库,转成Carbon对象后可以直接调用属性/方法做时间差计算:

use Carbon\Carbon;

$updatedAtStr = \DB::table('tickets')
        ->where('id', $ticket)
        ->value('updated_at');
$updatedAt = Carbon::parse($updatedAtStr);
// 直接获取时间戳
$timestamp = $updatedAt->timestamp;
// 计算天数差示例:和当前时间差
$diffDays = now()->diffInDays($updatedAt);

方法3:使用Eloquent模型(最简方式)

如果你的tickets表有对应的Eloquent模型,Laravel默认会把created_at/updated_at转为Carbon对象,直接调用属性即可:

// 假设模型名为Ticket
$ticket = Ticket::find($ticket);
$timestamp = $ticket->updated_at->timestamp;
// 计算两个时间的天数差
$anotherTime = Carbon::parse('2021-09-01 00:00:00');
$diffDays = $ticket->updated_at->diffInDays($anotherTime);

注意事项

  • 请确保项目config/app.php中的timezone配置和数据库存储的时间时区一致,避免转换出现时间偏差
  • 如果你坚持用pluck()方法,需要先从集合中取出对应值再转换:strtotime($updateRaw->first())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:15:00