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

Laravel Blade中用jQuery将Datetime转为时间戳的方法

解决Laravel返回的Datetime在JavaScript中转换为时间戳的问题

方案一:后端(Laravel)直接返回时间戳

这种方式更高效,还能避免前端处理的兼容性问题,优先推荐。

方法1:使用模型访问器

在Price模型中添加访问器,自动将created_at转换为时间戳:

class Price extends Model
{
    // ...

    public function getCreatedAtAttribute($value)
    {
        // 返回秒级时间戳(和PHP strtotime()输出一致)
        return strtotime($value);
        // 若需要毫秒级时间戳(匹配JS的getTime()格式),则:
        // return strtotime($value) * 1000;
    }
}

修改后,接口返回的JSON里created_at直接就是时间戳,前端可直接使用。

方法2:查询时手动转换

如果不想修改模型,可在查询阶段直接处理字段:

use Illuminate\Support\Facades\DB;

// ...

$priceall = Price::select('*', DB::raw('UNIX_TIMESTAMP(created_at) as created_at'))->get();

return response()->json([
    'priceall' => $priceall
]);

UNIX_TIMESTAMP()返回秒级时间戳,需要毫秒级的话乘以1000即可。

方案二:前端(JavaScript)转换时间戳

如果必须在前端处理,注意2023-01-12 10:49:00这种格式在部分旧浏览器中直接传入Date构造函数可能出错,建议先转为ISO标准格式再处理:

$.each(response.priceall, function(key, item) {
    // 将空格替换为T,转为ISO标准格式:2023-01-12T10:49:00
    const isoDate = item.created_at.replace(' ', 'T');
    // 获取毫秒级时间戳
    const timestamp = new Date(isoDate).getTime();
    // 若需要秒级时间戳(和PHP strtotime()一致),则:
    // const timestamp = Math.floor(new Date(isoDate).getTime() / 1000);
    
    // 此处使用转换后的timestamp即可
    console.log(timestamp);
});

现代浏览器直接使用new Date(item.created_at).getTime()也能正常工作,但替换空格为T能提升旧浏览器兼容性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 00:46:02