6、时间日期类型和函数
1、时间日期类型
ISO8610标准格式:YYYY-MM-DD HH:MM:SS 例如:2020-01-05 12:12:02
datetime:年月日时分秒 8字节
timestamp:年月日时分秒 4字节 时间戳类型 1970-2038年 如果做用户注册就不能用 年龄70年以前的很多
data:年月日 4字节
time:时分秒 3字节
year:年 1字节
如果牵涉到计算,就用mysql的数据类型 比如考勤系统(可以方便的用mysql的日期处理函数)
如果只是记录时间。可以int类型,再用编程语言格式化。
update student set brithday='2020-02-12 12:21:36' where id=5;
2、格式化输出
select date_format(brithday,'%Y年%m月%d天 %h:%i:%s') from student;//格式化日期和时间
select time_format(brithday,'%h:%i:%s') from student;//格式化时间
3、时间戳函数 timestamp()
二 常用函数
1)获取当前日期时间
select now();//取得当前日期和时间 select current_date();//取得当前日期 select current_time();//取得当前时间
2)拆分日期时间
年:year() 月:month() 日:day()
时:hour() 分:minute() 秒:second()
3)当前日期时间
SELECT now(),CURDATE(),CURRENT_DATE(),CURRENT_TIME(),NOW();
+---------------------+------------+----------------+----------------+---------------------+
| now() | CURDATE() | CURRENT_DATE() | CURRENT_TIME() | NOW() |
+---------------------+------------+----------------+----------------+---------------------+
| 2020-12-08 13:06:31 | 2020-12-08 | 2020-12-08 | 13:06:31 | 2020-12-08 13:06:31 |
+---------------------+------------+----------------+----------------+---------------------+
3)时间计算
当前时间是年月日中的第几天 select dayofweek(now());1-7 1是周日 6是周六 select weekday(now());0-6 0是周一 6是周日 select dayofmonth(now());//当前时间在月中是第几天 select dayofyear(now());//当前时间是一年中的第几天
五、定义变量
set @time = time(now());//定义变量 @time
select time_to_sec(@time);