CONVERT(VARCHAR(24),GETDATE(),23) -- yyyy-MM-dd常用相关类型
120 或者 20 | yyyy-mm-dd hh:mi:ss(24h) |
121 或者 21 | yyyy-mm-dd hh:mi:ss.mmm(24h) |
2.DATEDIFF 2个日期差
DATEDIFF(datepart,startdate,enddate) SELECT DATEDIFF(day,'2015-12-30','2015-12-29') AS DiffDate -- -1 SELECT DATEDIFF(week,'2015-12-01','2015-12-29') AS DiffDate -- 4 SELECT DATEDIFF(month,'2015-11-01','2015-12-29') AS DiffDate -- 1
3.DATEADD()
DATEADD(datepart,number,date)日期加/减 天/月/年
SELECT DATEADD(DAY,2,GETDATE()) --后天
datepart 缩写 年 yy, yyyy 季度 qq, q 月 mm, m 年中的日 dy, y 日 dd, d 周 wk, ww 星期 dw, w 小时 hh 分钟 mi, n 秒 ss, s 毫秒 ms 微妙 mcs 纳秒 ns
--昨天 Select * From TableName Where DateDiff(dd, DateTimCol, GetDate()) = 1 --明天 Select * From TableName Where DateDiff(dd, GetDate(), DateTimCol) = 1 --最近七天 Select * From TableName Where DateDiff(dd, DateTimCol, GetDate()) <= 7 --随后七天 Select * From TableName Where DateDiff(dd, GetDate(), DateTimCol) <= 7 --上周 Select * From TableName Where DateDiff(wk, DateTimCol, GetDate()) = 1 --本周 Select * From TableName Where DateDiff(wk, DateTimCol, GetDate()) = 0 --下周 Select * From TableName Where DateDiff(wk, GetDate(), DateTimCol ) = 1 --上月 Select * From TableName Where DateDiff(mm, DateTimCol, GetDate()) = 1 --本月 Select * From TableName Where DateDiff(mm, DateTimCol, GetDate()) = 0 --下月 Select * From TableName Where DateDiff(mm, GetDate(), DateTimCol ) = 1