计算两个时间相差多少年月日的sql算法
今天在CSDN上看到一个算法问题,描述如下:
如:起始时间 2011-1-1 截止日期 2011-2-1
两个时间比较相差 0年1个月
如:起始时间 2010-11-1 截止日期 2011-12-1
两个时间比较相差 1年1个月
怎么比较才能得出~ 相差多少年 多少个月
这个当然很简单, 一句SQL就可以了:
select ltrim(datediff(yy,@dt1,@dt2))+'年'+ltrim(datediff(mm,@dt1,@dt2)%12)+'月'
但是如果连几天也要计算呢?闲着没事自己随便在SQL Server下写了写,store procedures代码如下,应该没可以了:
CREATE PROCEDURE GetDateDiff
@fromDate nvarchar(10),
@toDate nvarchar(10)
AS
DECLARE @YearDiff INTEGER
DECLARE @MonthDiff INTEGER
DECLARE @DayDiff INTEGER
DECLARE @ToMonth INTEGER
DECLARE @FromDay INTEGER
DECLARE @ToDay INTEGER
SET @YearDiff = LTRIM(DATEDIFF(yy, @fromDate, @toDate))
SET @MonthDiff = LTRIM(DATEDIFF(mm, @fromDate, @toDate)%12)
SET @ToMonth = Month(cast(@toDate as Datetime))
SET @FromDay = Day(cast(@fromDate as Datetime))
SET @ToDay = Day(cast(@ToDate as Datetime))
IF (@ToDay - @FromDay) < 0
BEGIN
IF (@ToMonth - 1) = 1 OR (@ToMonth - 1) = 3 OR (@ToMonth - 1) = 5 OR (@ToMonth - 1) = 7 OR (@ToMonth - 1) = 8 OR (@ToMonth - 1) = 10 OR (@ToMonth - 1) = 12
BEGIN
SET @DayDiff = 31 + @Today - @FromDay
SET @MonthDiff = @MonthDiff -1
END
ELSE
BEGIN
SET @DayDiff = 30 + @Today - @FromDay
SET @MonthDiff = @MonthDiff -1
END
END
ELSE
BEGIN
SET @DayDiff = @Today - @FromDay
END
SELECT CAST(@YearDiff AS NVARCHAR(10)) + '年' + CAST(@MonthDiff AS NVARCHAR(10)) + '月' + CAST(@DayDiff AS NVARCHAR(10)) + '日'
如果有不正确,可以留言提出。