1.Sql 中常用时间处理函数
GETDATE() 返回当前的日期和时间
DATEPART() 返回日期/时间的单独部分
DATEADD() 返回日期中添加或减去指定的时间间隔
DATEDIFF() 返回两个日期直接的时间
DATENAME() 返回指定日期的指定日期部分的整数
CONVERT() 返回不同格式的时间
2.一些常用的日期格式
select DATEDIFF(day, '2019-08-20', getDate()); --获取指定时间单位的差值
SELECT DATEADD(MINUTE,-5,GETDATE()) --加减时间,此处为获取五分钟前的时间,MINUTE 表示分钟,可为 YEAR,MONTH,DAY,HOUR
select DATENAME(month, getDate()); --当前月份
select DATENAME(WEEKDAY, getDate()); --当前星期几
select DATEPART(month, getDate()); --当前月份
select DAY(getDate()); --返回当前日期天数
select MONTH(getDate()); --返回当前日期月数
select YEAR(getDate()); --返回当前日期年数
SELECT CONVERT(VARCHAR(16),GETDATE(),120) --时间格式转化 获取精确到分的时间 2019-08-20 14:53
SELECT CONVERT(VARCHAR(24),GETDATE(),102) --2006.05.16
SELECT CONVERT(VARCHAR(20),GETDATE(),114) --15:31:39:227
SELECT CONVERT(VARCHAR(16),GETDATE(),0) --08 20 2019 3:02
SELECT CONVERT(VARCHAR(10),GETDATE(),5) --20-08-19
SELECT CONVERT(VARCHAR(16),GETDATE(),11) --19/08/20
SELECT CONVERT(VARCHAR(16),GETDATE(),12) --
SELECT CONVERT(VARCHAR(22),GETDATE(),20) --2019-08-20 15:06:04 若为16 则为精确到分
SELECT CONVERT(VARCHAR(24),GETDATE(),21) --2019-08-20 15:06:04.590
3.日期单位及其缩写
日期单位
|
缩写
|
year
|
yyyy 或yy
|
quarter
|
qq,q
|
month
|
mm,m
|
dayofyear
|
dy,y
|
day
|
dd,d
|
week
|
wk,ww
|
weekday
|
dw
|
Hour
|
hh
|
minute
|
mi,n
|
second
|
ss,s
|
millisecond
|
ms
|
declare @date datetime
set @date=GETDATE()
select datepart(year,@date)iYear,datepart(month,@date)iMonth,datepart(day,@date)iDay,datepart(quarter,@date)iDuarter, datepart(dayofyear,@date)iDayofyear,datepart(weekday,@date)iWeekday,
datepart(week,@date)iWeek,datepart(Hour,@date)iHour,datepart(minute,@date)iMinute,datepart(SECOND,@date)iSecond,datepart(millisecond,@date)iMillisecond
--采用简写格式
declare @date datetime
set @date=GETDATE()
select datepart(yyyy,@date)iYear,datepart(mm,@date)iMonth,datepart(d,@date)iDay,datepart(qq,@date)iDuarter, datepart(dy,@date)iDayofyear,datepart(dw,@date)iWeekday,
datepart(ww,@date)iWeek,datepart(hh,@date)iHour,datepart(mi,@date)iMinute,datepart(s,@date)iSecond,datepart(ms,@date)iMillisecon
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoQAAAAxCAYAAABDL7igAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAq3SURBVHhe7ZzLrtxGDob1TnmnvMsAs519FtkFs5oHMbw42zhOnNti4HO/dB9DcyowAQ5D1l3VLOn/gS9dJEsSySq1K53Ay+pM//jnv9b3799n891336/ffPOtiXbNaO7u7v6q6/r6GgAAAADAHS4PhO/evdsVOBACAAAAwDMuD4QAAAAAAGAc7g6EEARBEARB0FgtP/z7PysAAAAAADguXX4hvL29/TqaRzPmbMlrLXvqcamOXHupsE/mEfL1J9QI9VDoMQ6EO5DXWo78Eh+59lJhn8wj5OtPqBHqodDjLgfCm5ubr6N5NGPOlrzWsqcel+rItZcK+2QeIV9/Qo1QD4Ue40C4A3mt5cgv8ZFrLxX2yTxCvv6EGqEeCj3GgXAH8lrLkV/iI9deKuyTeYR8/Qk1Qj0UetzlQBj+QsPZNGPOlrzWsqcel+rItZcK+2QeIV9/Qo1QD4UedzkQfv78+evo71qW/39EsMnHx6PlKefWe9bU0vrMHHnNa4S81j7qOSUq7ZX2WapwXeranDmt8lq7pZp9TWp5bq1q89VylbYXldQYRLURo1Xz3C3Xkebk+kmW/5KK5ZtS6PHy9HxaW3h9/bL+/sef6/n8qsY1QsL8czSlOVOT5bgW7frae7b0X4574jWvre7LOX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