MSSQL - 将自1970年以来的毫秒转换为datetime2

时间:2013-02-05 20:58:02

标签: sql sql-server-2008 datetime

考虑以下查询(在MSSQL 2008中):

SELECT dateModified FROM SomeTable;

以javascript格式返回浮点数(自1970年以来的毫秒数):

dateModified 
============ 
1301598290687 
1071003581343 
1311951478593

如何在select?

中将其转换为datetime2

2 个答案:

答案 0 :(得分:10)

使用@Mikeal Eriksson's answer here中的公式。

我会将float转换为bigint,然后创建datetime:

select 
  DATEADD(MILLISECOND, 
          cast(dateModified as bigint) % 1000, 
          DATEADD(SECOND, cast(dateModified as bigint) / 1000, '19700101'))
from sometable

请参阅SQL Fiddle with Demo

答案 1 :(得分:-1)

一些Oracle示例 - 使用eqivalent:

替换to_date()
  SELECT (1301598290687/60/60/24/1000) as Days
   , to_date('01-01-1970','dd-mm-yyyy') as start_date
   , to_date('01-01-1970','dd-mm-yyyy')+(1301598290687/60/60/24/1000) as converted_date
  FROM dual
  /

DAYS                START_DATE      CONVERTED_DATE
---------------------------------------------------------
15064.7950310995    1/1/1970        3/31/2011 7:04:51 PM

创建双表:

CREATE TABLE DUAL
(
DUMMY VARCHAR(1)
)
GO
INSERT INTO DUAL (DUMMY)
 VALUES ('X')
GO