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) www.2cto.com
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) | www.2cto.com
+-----------------------------------------+
| 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;
+---------+ www.2cto.com
| 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) |
+----------+ www.2cto.com
| 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