6

我有两个日期:

2012-10-04 12:48:56:0002012-10-04 12:48:58:000

预期结果是
2012-10-04 12:48:57:000


2012-10-04 12:48:56:0002012-10-04 12:48:56:010

预期结果是
2012-10-04 12:48:56:005

(日期是虚构的,因为在 sql server 中毫秒部分 DATETIME 数据类型增加了 3 )

4

6 回答 6

8

用你自己的日期...

SELECT DATEADD(ms, 
          DATEDIFF(ms,'2012-10-04 12:48:56:000', '2012-10-04 12:48:58:000')/2,
         '2012-10-04 12:48:56:000')
于 2012-10-05T11:40:18.007 回答
1

像这样的东西:

with sample_data (start_dt, end_dt) as 
( 
   select cast('2012-10-04 12:48:56:000' as datetime), cast('2012-10-04 12:48:58:000' as datetime)
   union all
   select cast('2012-10-04 12:48:56:000' as datetime), cast('2012-10-04 12:48:56:010' as datetime)
)
select start_dt, end_dt, dateadd(millisecond, datediff(millisecond, start_dt, end_dt) / 2, start_dt)
from sample_data

尽管第二对计算不正确。可能是因为 3 毫秒的分辨率。

于 2012-10-05T11:46:19.747 回答
1
declare @date1 datetime;
declare @date2 datetime;

set @date1 = '2012-10-04 12:48:56:000';
set @date2 = '2012-10-04 12:48:58:000';

select DateAdd(ms, DateDiff(ms, @date1, @date2)/2, @date1)
于 2012-10-05T11:46:33.297 回答
1

我需要能够使用 MySQL 和 MariaDB 做到这一点。这是有效的:

SELECT DATE_ADD('2012-10-06 12:48:58.000', INTERVAL time_to_sec(TIMEDIFF('2012-10-04 12:48:56.000', '2012-10-06 12:48:58.000'))/2 SECOND)

结果:2012-10-05 12:48:57.000000

于 2019-03-14T00:55:19.857 回答
0
-- let's day d1 and d2 are DateTime variables (d1 < d2)

-- get the differnce in milliseconds 
-- (you can change it but be careful with oveflow situations)
declare @diff integer = datediff (ms, @d1, @d2)
-- the middle is the first date + half of the difference
declare @middle DateTime = dateadd (ms, @diff / 2, @d1)
于 2012-10-05T11:48:37.443 回答
-1

试试这个(你可以根据你想要的准确度来替换日期部分):

DateAdd(ms, DateDiff(ms, date1, date2), date1)/2
于 2012-10-05T11:38:42.053 回答