sqlserver计算两个日期之差,精确到毫秒
declare @starttime datetime,@endtime datetime
set @starttime='2012-10-07 10:57:23.957'
set @endtime ='2012-11-08 08:31:03.224'
如题,我要计算@endtime与@starttime的差值;应该得到 几天 几小时 几分 几秒 几毫秒
select datediff(part,@starttime,@endtime)
part使用day计算出来是32天,不对;
part使用ss,ss最大是60几天,超出的话不对;
part使用ms,ms最大是24小时多少多少,超出不对。
大神们,你们是怎么做的啊?
[最优解释]
declare @starttime datetime,@endtime datetime,@T datetime
set @starttime='2012-10-07 10:57:23.957'
set @endtime ='2012-11-08 08:31:03.224'
select @T = cast( cast(@endtime as float)-cast(@starttime as float) as datetime)
select cast(datediff(day,'1900-01-01',@T)as varchar(10))+'天'+cast(datepart(hh,@T)as varchar(10))
+'小时'+cast(datepart(mi,@T)as varchar(10))+'分'+cast(datepart(ss,@T)as varchar(10))+'秒'
+cast(datepart(ms,@T)as varchar(10))+'毫秒'
/*----------------------------
31天21小时33分39秒267毫秒
(1 行受影响)
*/
declare @starttime datetime2,@endtime datetime2
set @starttime='2012-10-07 10:57:23.957'
set @endtime ='2012-11-08 08:31:03.224'
SELECT CASE WHEN DATEDIFF(hour, @starttime, @endtime) < 24
THEN CONVERT(VARCHAR(10), DATEDIFF(DAY, @starttime, @endtime) - 1)
ELSE CONVERT(VARCHAR(10), DATEDIFF(DAY, @starttime, @endtime))
END + '天' + CONVERT(VARCHAR(10), DATEDIFF(hour, @starttime, @endtime)
% 24) + '时' + CONVERT(VARCHAR(10), DATEDIFF(mm, @starttime, @endtime)
% 60) + '分' + CONVERT(VARCHAR(10), DATEDIFF(ss, @starttime, @endtime)
% 60) + '秒'
/*
------------------------------------------------
32天22时1分40秒
(1 行受影响)
*/
declare @starttime datetime,@endtime datetime
set @starttime='2012-10-07 10:57:23.957'
set @endtime ='2012-11-08 08:31:03.224'
SELECT CONVERT(VARCHAR(10),DATEDIFF(DAY,@starttime,@endtime))+'天'+CONVERT(VARCHAR(10),DATEDIFF(hour,@starttime,@endtime)%24)+'时'+
CONVERT(VARCHAR(10),DATEDIFF(mm,@starttime,@endtime)%60)+'分'+CONVERT(VARCHAR(10),DATEDIFF(ss,@starttime,@endtime)%60)+'秒'
/*
------------------------------------------------
32天22时1分40秒
(1 行受影响)
*/
select DATEDIFF(nanosecond,'2012-10-07 10:57:23.957','2012-10-07 10:57:25.957') 毫秒
----------------------------------------
毫秒
-----------
2000000000
(1 行受影响)