关于日期函数查询总结

一:获取时间日期

1. 获取当前的日期和时间:2017-05-02 22:11:38

select now()  最优选择    /current_timestamp,localtime,localtimestamp 及其函数

2. 获取间隔时间(3s前后时间):2017-05-02 22:30:10    0     2017-05-02 22:30:13

select sysdate(), sleep(3), sysdate()

3. 获取当前日期:2017-05-02

select curdate();  /current_date及其函数

4.获取时间:22:40:43

select curtime(); /current_time及其函数

 

总结:当前时间前缀表示时刻都是cur/current_,后面表示格式就是timestamp,date,time(看需要),若是utc时间前缀就是utc_,utc适合国家的使用,因为跨时区。

二:获取时间的某部分

1. 选取日期时间的各个部分:日期、时间、年、季度、月、日、小时、分钟、秒、微秒

set @dt = '2017-05-02 07:15:30.123456';

select date(@dt); -- 2017-05-02
select time(@dt); -- 07:15:30.123456
select year(@dt); -- 2017
select quarter(@dt); -- 2
select month(@dt); -- 5
select week(@dt); -- 18 从一月一号算起
select day(@dt); -- 10
select hour(@dt); -- 7
select minute(@dt); -- 15
select second(@dt); -- 30
select microsecond(@dt); -- 123456 微秒

MySQL Extract() 函数除了没有date(),time() 的功能外,其他功能一应具全。

Extract()可以实现同样功能,如select extract(hour from @dt); -- 7 。而且可以使实现指定范围,如:select extract(day_microsecond from @dt); -- 02071530123456

2. 一周、一月、一年中的位置 (dayof+定位的类型,week也可以)

set @dt = '2017-05-03';

select dayofweek(@dt); -- 4    是一周中的第 4 天,周三(1 = Sunday, 2 = Monday, ..., 7 = Saturday)      weekday:(0 = Monday, 1 = Tuesday, ..., 6 = Sunday)
select dayofmonth(@dt); -- 3   一月中的第 3 天
select dayofyear(@dt); -- 123  一年中的第 123 天。

select weekofyear(@dt); -- 18

select dayname(@dt); -- Wednesday
select monthname(@dt); -- May

3. 获取最后一天

select last_day('2008-02-01'); -- 2008-02-29

 如:得到当前月份中有多少天     select day(last_day(now())) as days; --31

 

posted @ 2017-05-02 23:03  x.cube  阅读(423)  评论(0编辑  收藏  举报