欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

MySQL中常用到的关于时间的SQL

程序员文章站 2022-05-10 09:34:27
-- 今天 SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00') AS dayStart;SELECT DATE_FORMAT(NOW(),'%Y-%m-%d 23:59:59') AS dayEnd; -- 昨天SELECT DATE_FORMAT( DATE ......

-- 今天
select date_format(now(),'%y-%m-%d 00:00:00') as daystart;
select date_format(now(),'%y-%m-%d 23:59:59') as dayend;

MySQL中常用到的关于时间的SQL

 

-- 昨天
select date_format( date_sub(curdate(), interval 1 day), '%y-%m-%d 00:00:00') as yesterdaystart;
select date_format( date_sub(curdate(), interval 1 day), '%y-%m-%d 23:59:59') as yesterdayend;

MySQL中常用到的关于时间的SQL

 

-- 上周
select date_format( date_sub( date_sub(curdate(), interval weekday(curdate()) day), interval 1 week), '%y-%m-%d 00:00:00') as lastweekstart
select date_format( subdate(curdate(), weekday(curdate()) + 1), '%y-%m-%d 23:59:59') as lastweekend;

MySQL中常用到的关于时间的SQL

 

 

-- 本周
select date_format(date_sub(curdate(), interval weekday(curdate()) day), '%y-%m-%d 00:00:00') as weekstart;
select date_format(date_add(subdate(curdate(), weekday(curdate())), interval 6 day), '%y-%m-%d 23:59:59') as weekend;

MySQL中常用到的关于时间的SQL

 

 

-- 上月
select date_format( date_sub(curdate(), interval 1 month), '%y-%m-01 00:00:00') as lastmonthstart;
select date_format( last_day(date_sub(curdate(), interval 1 month)), '%y-%m-%d 23:59:59') as lastmonthend;

MySQL中常用到的关于时间的SQL

 

 

-- 本月
select date_format(curdate(), '%y-%m-01 00:00:00') as monthstart;
select date_format(last_day(curdate()), '%y-%m-%d 23:59:59') as monthend;

MySQL中常用到的关于时间的SQL

 

 

--获取今天时间年月日

--select curdate() as nowdate

MySQL中常用到的关于时间的SQL

 

 

-- 获取现在时间(年月日时分秒)

select date_format(now(),'%y-%m-%d %h:%i:%s') as nowtime

MySQL中常用到的关于时间的SQL

 

 

--获取本月有多少天

select datediff(date_add(curdate() - day(curdate()) + 1, interval 1 month),
date_add(curdate(), interval -day(curdate()) + 1 day)) as day
from dual;

MySQL中常用到的关于时间的SQL

 

 获取某个月的每一天或当前月的每一天日期

此sql参考自 https://blog.csdn.net/qq_38798251/article/details/89140471

select date
from (select date_add(t1.dayed, interval t2.number day) date
from (select date_add(curdate(), interval -day(curdate()) + 1 day) dayed) t1,
(select @xi := @xi + 1 as number
from (select 1 union select 2 union select 3 union select 4) xc1,
(select 1
union
select 2
union
select 3
union
select 4
union
select 5
union
select 6
union
select 7
union
select 8) xc2,
(select @xi := -1) xc0) t2
where date_add(t1.dayed, interval t2.number day)) time
where substring(date, 1, 7) = substring(curdate(), 1, 7)

MySQL中常用到的关于时间的SQL

 

 

另有一些未用到的sql 做个记录

1、查询当前时间3天前的时间点

select date_sub(now() ,interval 3 day)

2.查询当前时间的时间3天之后的时间点

select data_sub(now(),interval -3 day)

3.查询当前时间3个月之前的时间点

select data_sub(now(),interval 3 month)

4.查询当前时间3个月之后的时间点

select data_sub(now,interval -3 month)