SQlServer date subtraction (interval) dateadd, datediff function

Address of Bai Yuqing workstation: http://www.byqws.com/blog/1044.html

1. Use of dateadd function

The dateadd() function adds or subtracts a specified time interval from a date.

dateadd(datepart,number,date)

The date  parameter is a valid date expression. number  is the number of intervals you wish to add; this number is positive for times in the future and negative for times in the past.

Examples are as follows:

1. One year before the current time, one year after the current time

select '一年前' type,dateadd(year, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一年后' type,dateadd(year, 1, GETDATE()) time

2. One month before the current time, one month after the current time

select '一月前' type,dateadd(month, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一月后' type,dateadd(month, 1, GETDATE()) time

3. One day before the current time, one day after the current time

select '一天前' type,dateadd(day, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一天后' type,dateadd(day, 1, GETDATE()) time

4. One week before the current time, one week after the current time

select '一周前' type,dateadd(week, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一周后' type,dateadd(week, 1, GETDATE()) time

5. One hour before the current time, one hour after the current time

select '一小时前' type,dateadd(hour, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一小时后' type,dateadd(hour, 1, GETDATE()) time

6. One minute before the current time, one minute after the current time

select '一分钟前' type,dateadd(minute, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一分钟后' type,dateadd(minute, 1, GETDATE()) time

7. One second before the current time, one second after the current time

select '一秒前' type,dateadd(second, -1, GETDATE()) time
union all
select '当前时间' type,GETDATE() time
union all
select '一秒后' type,dateadd(second, 1, GETDATE()) time

Second, the use of datediff function

The datediff() function returns the interval between two dates, the default is the number of days between

datediff(datepart, date1,date2)

date1: start time; date2: end time

Examples are as follows:

select dateadd(year, -1, GETDATE()) 开始日期,GETDATE() 结束日期,'前后2个时间相差' + convert(varchar(1),datediff(year, dateadd(year, -1, GETDATE()),GETDATE()))+ '年' type
union all
select dateadd(year, -1, GETDATE()) 开始日期,GETDATE() 结束日期,'前后2个时间相差' + convert(varchar(10),datediff(month, dateadd(year, -1, GETDATE()),GETDATE()))+ '月' type
union all
select dateadd(year, -1, GETDATE()) 开始日期,GETDATE() 结束日期,'前后2个时间相差' + convert(varchar(10),datediff(day, dateadd(year, -1, GETDATE()),GETDATE()))+ '天' type

Guess you like

Origin blog.csdn.net/qq_41674785/article/details/129953754