Laravel Mysql语句中时间戳/日期格式相互转换

Song3836 次浏览0个评论2020年06月03日

一、Mysql中时间戳和日期的转换

熟悉Mysql的都知道我们可以使用UNIX_TIMESTAMPFROM_UNIXTIME进行时间戳和日期的转换

select UNIX_TIMESTAMP('2020-06-01 12:25:00');
结果:1590985500

案例: 
select id,username,UNIX_TIMESTAMP(updated_at) AS updated_date from users;

2.时间戳转日期:


select FROM_UNIXTIME(1545711900);
结果:2020-06-01 12:25:00
案例: 
select id,username,FROM_UNIXTIME(created_at,'%Y-%m-%d %H:%i:%s') from users;

二、Laravel中数据库时间戳和日期格式的转换

我们可以使用原始表达式Model模型进行在日期和时间之间转化:

# 时间戳转日期
DB::raw("date_format(from_unixtime(created_at),'%Y-%m-%d %H:%i:%s') as created_date")
# 日期转时间戳
DB::raw("from_timestamp(updated_at) as updated_date")

然后我们结合真实场景使用:

DB::table('users')->select(DB::raw("date_format(from_unixtime(created_at),'%Y-%m-%d %H:%i:%s') as created_date"),"created_at","province")->get();

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文

    当前暂无更多相关好文推荐...