几个日期类型
日期类型 | 存储空间 | 日期格式 | 日期范围 |
---|---|---|---|
datetime | 8 bytes | YYYY-MM-DD HH:MM:SS | 1000-01-01 00:00:00 ~ 9999-12-31 23:59:59 |
timestamp | 4 bytes | YYYY-MM-DD HH:MM:SS | 1970-01-01 00:00:01 ~ 2038 |
date | 3 bytes | YYYY-MM-DD | 1000-01-01 ~ 9999-12-31 |
year | 1 bytes | YYYY | 1901 ~ 2155 |
CREATE TABLE `t_ian_test` (
`id` bigint(20) NOT NULL,
`name` varchar(64) NOT NULL,
`startTime` datetime NOT NULL,
`endTime` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `t_ian_test` VALUES (1, '牛', '2018-01-21 10:20:09', '2018-01-21 10:20:09');
INSERT INTO `t_ian_test` VALUES (2, '年', '2021-01-29 10:20:30', '2021-01-29 10:20:30');
INSERT INTO `t_ian_test` VALUES (3, '大', '2021-01-28 19:47:37','2021-01-28 19:47:37');
INSERT INTO `t_ian_test` VALUES (4, '吉', '2021-01-28 19:51:01','2021-01-28 19:51:01');
查询时间段
查询 28 号这天的所有数据 - fail
select * from t_ian_test where startTime between '2021-01-28' and '2021-01-28';
select * from t_ian_test where startTime between '2021-01-28 00:00:00' and '2021-01-28 00:00:00';
查询 28 号这天的所有数据 - success
select * from t_ian_test where startTime between '2021-01-28 19:47:37' and '2021-01-28 19:51:01';
查询 28 号这天的所有数据 - success
select * from t_ian_test where startTime between '2021-01-28' and '2021-01-29';
查询 28 号这天的所有数据 - success
select * from t_ian_test where startTime between '2021-01-28' and date_add('2021-01-28', interval 1 day);
获取系统当前时间的函数:
select CURDATE();
select NOW();
获取时间差的函数:
period_diff()
datediff(date1,date2)
timediff(time1,time2)
日期加减函数:
date_sub() 、adddate()、addtime()、period_add(P,N)
# 加1天
select date_add(now(), interval 1 day);
#加1小时
select date_add(now(), interval 1 hour);
# 加1分钟
select date_add(now(), interval 1 minute);
#加1秒
select date_add(now(), interval 1 second);
#加1毫秒
select date_add(now(), interval 1 microsecond);
#加1周
select date_add(now(), interval 1 week);
#加1月
select date_add(now(), interval 1 month);
#加1季
select date_add(now(), interval 1 quarter);
#加1年
select date_add(now(), interval 1 year);
时间格式转化函数:
date_format(date, format)
str_to_date(str, format)
unix_timestamp()
from_unixtime(unix_timestamp, format)