mysql日期函数
current_date() | 当前日期 2020-08-01 |
---|---|
current_time() | 当前时间 18:51:58 |
now( ) | 当前时间 2020-08-01 18:51:58 |
current_timestamp() | 当前时间 2020-08-01 18:51:58 |
date_add(date2,interval d_value d_type) | 在date2中加上一个时间 |
date_sub(date2,interval d_value d_type) | 在date2上减去一个时间 |
datediff(date1,date2) | 两个日期差(结果是天) |
timediff(date1,date2) | 两个时间差(多少小时多少分钟多少秒) |
date(datetime) | 返回datetime的日期部分 |
year(datetime) 和 month(datetime) | 返回datetime的 年 或 月 |
unix_timestamp() | 返回时间戳 1970-1-1 00:00:00 到现在的无符号整数(秒数) |
from_unixtime(unix_timestamp()) | 对时间戳进行格式化(可自定义) |
第一组函数
current_date() | 当前日期 2020-08-01 |
---|---|
current_time() | 当前时间 18:51:58 |
now( ) | 当前时间 2020-08-01 18:51:58 |
current_timestamp() | 当前时间 2020-08-01 18:51:58 |
基本用法
//查询数据
ysql> select current_date(),current_time(),current_timestamp(),now();
+----------------+----------------+---------------------+---------------------+
| current_date() | current_time() | current_timestamp() | now() |
+----------------+----------------+---------------------+---------------------+
| 2020-08-02 | 09:20:49 | 2020-08-02 09:20:49 | 2020-08-02 09:20:49 |
+----------------+----------------+---------------------+---------------------+
1 row in set (0.00 sec)
//插入数据(只举一个例子 其他类似)
mysql> create table tt(id int, birthday date);
Query OK, 0 rows affected (0.11 sec)
mysql> insert into tt values(1, current_date());
Query OK, 1 row affected (0.04 sec)
mysql> select * from tt;
+------+------------+
| id | birthday |
+------+------------+
| 1 | 2020-08-01 |
+------+------------+
1 row in set (0.00 sec)
第二组函数
date_add(date2,interval d_value d_type) | 在date2中加上一个时间 |
---|---|
date_sub(date2,interval d_value d_type) | 在date2上减去一个时间 |
datediff(date1,date2) | 两个日期差(结果是天) |
timediff(date1,date2) | 两个时间差(多少小时多少分钟多少秒) |
细节说明
- date_add() 和 date_sub() 功能一样,其中interval后面可以是 year day minute second
- datediff(date1,date2) 得到的是天数,而且是date1-date2,因此可以是负数
- timediff(date1,date2)| 得到的是时分秒,而且是date1-date2,因此可以是负数
- 这位四个函数的日期类型可以是 date datetime timestamp
- 这几个函数经常在论坛留言表中使用
基本用法
// date_add(date2,interval d_value d_type)
mysql> select date_add('2011-11-11',interval 10 day);
+----------------------------------------+
| date_add('2011-11-11',interval 10 day) |
+----------------------------------------+
| 2011-11-21 |
+----------------------------------------+
1 row in set (0.00 sec)
mysql> select date_add('2011-11-11',interval -10 day);
+-----------------------------------------+
| date_add('2011-11-11',interval -10 day) |
+-----------------------------------------+
| 2011-11-01 |
+-----------------------------------------+
1 row in set (0.00 sec)
// date_sub(date2,interval d_value d_type)
mysql> select date_sub('2011-11-11',interval 10 day);
+----------------------------------------+
| date_sub('2011-11-11',interval 10 day) |
+----------------------------------------+
| 2011-11-01 |
+----------------------------------------+
1 row in set (0.00 sec)
mysql> select date_sub('2011-11-11',interval -