将datediff显示为秒,毫秒

时间:2013-03-27 13:56:02

标签: sql sql-server tsql datetime

我正在尝试计算两个日期时间值之间的差异。

我尝试了datediff(s, begin,end)datediff(ms, begin,end)但是我想将差异作为seconds,milliseconds返回,如下所示:

4,14
63,54

3 个答案:

答案 0 :(得分:27)

SELECT 
  DATEDIFF(MILLISECOND, begin, end) / 1000, 
  DATEDIFF(MILLISECOND, begin, end) % 1000
FROM ...;

如果您绝对必须在SQL查询中将其形成为字符串(您的表示层不能这样做吗?),那么:

SELECT 
  CONVERT(VARCHAR(12),  DATEDIFF(MILLISECOND, begin, end) / 1000)
  + ',' 
  + RIGHT('000' + CONVERT(VARCHAR(4), DATEDIFF(MILLISECOND, begin, end) % 1000), 3)
FROM ...;

另外,我真的希望你的列名比beginend更好。

答案 1 :(得分:4)

实际上,标记的答案会产生错误的结果,以毫秒为单位1 - 99:

Example 1 second, 27 milliseconds:
1) DATEDIFF % 1000 will return 27
2) CONVERT will convert to '27'
3) String concatenation will build '1' + ',' + '27'
4) Result: '1.27' which means 270ms rather than 27ms

不要忘记将毫秒填充为三个零:

DECLARE @start datetime2(7) = '2015-07-03 09:24:33.000'
DECLARE @end datetime2(7) = '2015-07-03 09:24:34.027'

SELECT 
    CAST (DATEDIFF(SECOND, @start, @end) AS nvarchar(3)) + N'.' +
    RIGHT('000' + CAST((DATEDIFF(MILLISECOND, @start, @end) % 1000) AS nvarchar(3)), 3)

答案 2 :(得分:0)

DATEDIFF在MySQL中仅接受两个参数。这对我有用:

TIMESTAMPDIFF(SECOND, NOW(), '2019-09-09 18:52:00')