MYSQL时间函数用法宝典_MySQL
时间:2021-07-01 10:21:17
帮助过:33人阅读
bitsCN.com
MYSQL时间函数用法宝典 测试表:root@test 16:50>desc t1;+-------+----------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+-------+----------+------+-----+---------+-------+| id | int(11) | YES | | NULL | | | t1 | datetime | YES | | NULL | | +-------+----------+------+-----+---------+-------+2 rows in set (0.00 sec) root@test 16:50>select * from t1;+------+---------------------+| id | t1 |+------+---------------------+| 1 | 2012-05-13 12:27:12 | | 2 | 2012-05-13 12:27:12 | | 3 | 2012-05-13 12:27:12 | +------+---------------------+ (1),DATE_ADD(date,INTERVAL expr unit) root@test 16:50>SELECT DATE_ADD(t1,INTERVAL -1 YEAR) FROM t1;+-------------------------------+| DATE_ADD(t1,INTERVAL -1 YEAR) |+-------------------------------+| 2011-05-13 12:27:12 | | 2011-05-13 12:27:12 | | 2011-05-13 12:27:12 | +-------------------------------+ root@test 17:21>SELECT DATE_ADD('2008-01-02', INTERVAL 31 DAY);+-----------------------------------------+| DATE_ADD('2008-01-02', INTERVAL 31 DAY) | +-----------------------------------------+| 2008-02-02 | +-----------------------------------------+ (2),DATE_FORMAT(date,format)
format格式有很多种,具体可以MYSQL手册。该函数让时间以某种格式显示root@test 17:00>SELECT DATE_FORMAT(t1, '%H:%i:%s') from t1;+-----------------------------+| DATE_FORMAT(t1, '%H:%i:%s') |+-----------------------------+| 12:27:12 | | 12:27:12 | | 12:27:12 | +-----------------------------+(3)datediff(expr1,expr2)用于计算两个时间的相差的天数 root@test 17:01>select datediff(t1,now()) from t1;+--------------------+| datediff(t1,now()) |+--------------------+| -23 | | -23 | | -23 | +--------------------+ 4,返回当前日期curdate(),curtime()返回当前时间,now()返回当前的日期和时间。
5,返回日期中的年份year(),返回日期中月份month(),返回日期中的天day(),返回日期中时间time()。root@test 17:08>select day(t1) from t1;+---------+ | day(t1) |+---------+| 13 | | 13 | | 13 | +---------+3 rows in set (0.00 sec) root@test 17:13>select time(t1) from t1; +----------+| time(t1) |+----------+| 12:27:12 | | 12:27:12 | | 12:27:12 | +----------+3 rows in set (0.00 sec) root@test 17:13>select month(t1) from t1; +-----------+| month(t1) |+-----------+| 5 | | 5 | | 5 | +-----------+3 rows in set (0.00 sec)root@test 17:13>select year(t1) from t1; +----------+| year(t1) |+----------+ | 2012 | | 2012 | | 2012 | +----------+3 rows in set (0.00 sec)6,week()计算当前日期为本年度的多少周 root@test 17:16>select week('2012-06-05'); +--------------------+| week('2012-06-05') |+--------------------+| 23 | +--------------------+1 row in set (0.00 sec) 作者 alang85 bitsCN.com