日期和时间处理函数
一般应用程序不使用用来存储日期和时间的格式,因为日期和时间函数总是被用来读取、统计和处理这些值。因此日期和时间函数在mysql中有重要作用
函数 | 说明 |
AddDate() | 增加一个日期(天、周等) |
AddTime() | 增加一个时间(时、分等) |
curdate() | 返回当前日期 |
curtime() | 返回当前时间 |
date() | 返回日期时间的日期部分 |
datediff() | 计算两个日期之差 |
date_add() | 高度灵活的日期运算函数 |
date_format() | 返回一个格式化的日期或者时间串 |
day() | 返回一个日期的天数部分 |
dayofweek() | 对于一个日期,返回对应的星期几 |
hour() | 返回一个时间的小时部分 |
minute() | 返回一个时间的分钟部分 |
month() | 返回一个时间的月份部分 |
now() | 返回当前日期和时间 |
second() | 返回一个时间的秒部分 |
time() | 返回一个日期时间的时间部分 |
year() | 返回一个日期的年份部分 |
mysql使用的日期格式,无论什么时候指定一个日期,不管是插入还是更新值还是用where子句进行过滤,日期必须为yyyy-mm-dd
select cust_id,order_num from orders where order_date=’2005-09-01’;
上句即时能够正常运行,也不推荐使用,因为使用where order_date =’2005-09-01’不可靠,如果order_date数据类型是datetime,这种类型存储时间含有00:00:00,假如时间为2005-09-01 12:13:26 如果再使用where order_date =’2005-09-01’,就会出错的
因此要使用date(),date(order_date)指示mysql只提取日期部分语句如下
select cust_id,order_num from orders where date(order_date)=’2005-09-01’;
另外 假如要检索2005年9月份的所有订单,简单的相等测试不行的,可以有一下方法
select cust_id,order_num from orders where date(order_date) between’2005-09-01’and ‘2005-09-30’;使用between and 进行检索
还有一种方法,不需要记住每月有多少天,不需要担心闰年2月的办法 如下
select cust_id,order_num from orders where year(order_date)=2005 and month(order_date)=9;