PHP与MySQL日期时间处理概述
在时间比较查询的时候,int的效率明显更高。祥文见https://www.jb51.net/article/29767.htm
然而在实际项目开发或直接在数据库中审查数据时,纯数字的时间戳往往令人困惑。例如,当我们希望
查询某位用户的注册具体时间时:
select reg_time from t_xx_users where user_id=1;
此时返回的结果为int类型的数值,无法直观地识别出具体的年月日时分秒。因此,这就引出了datetime与int之间相互转化的需求,
同时PHP中的date()和time()等函数也涉及相应的转换逻辑。以下对相关内容进行简要总结:
(1) PHP层面
获取int值:
time():该函数返回自Unix纪元(格林威治时间1970年1月1日00:00:00)起至当前时刻的秒数。
若需获取从1970年1月1日到2012-2-10的秒数,可通过strtotime()函数实现,即调用:strtotime('2012-2-10');
获取date字符串值:
string date ( string format [, int timestamp] )
例如:直接调用date()可返回当前时间的默认格式字符串;也可以指定特定格式,如:date('Y-m-d',strtotime('2012-2-10'));
时间运算操作:
date('Y-m-d h:i:s',strtotime('+1 week'));
date('Y-m-d h:i:s',strtotime('+5 hours'));
date('Y-m-d h:i:s',strtotime('next Monday));
date('Y-m-d h:i:s',strtotime('last Sunday'));
date('Y-m-d h:i:s',strtotime('+ 1 day',12313223));!!详见 int strtotime ( string time [, int now] )
(2) MySQL层面:
将int转换为datetime
select from_unixtime(int_time) from table;
将datetime转换为int:
select unix_timestamp(date_time) from table;
时间相关操作:
select dayofweek('2012-2-2'); 返回该日期是一周中的第几天
select dayofmonth('2012-2-2'); 返回该日期是本月中的第几天
select dayofyear('2012-2-2'); 返回该日期是本年中的第几天
类似功能的函数还包括:month()、day()、hour()、week()等......
增加天数:date_add(date,interval 2 days);
减少天数:date_sub(date,interval 2 days);
时间格式化:
date_format(date,format)
select DATE_FORMAT('1997-10-04 22:23:00','%W %M %Y');
其他实用函数:TIME_TO_SEC()、SEC_TO_TIME()等...