Luke Belbina
Luke Belbina

Reputation: 5869

MSSQL - Convert milliseconds since 1970 to datetime2

Consider the following query (in MSSQL 2008):

SELECT dateModified FROM SomeTable;

This returns floats in javascript format (milliseconds since 1970):

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

How can I convert this to a datetime2 right in the select?

Upvotes: 4

Views: 14761

Answers (2)

Art
Art

Reputation: 5792

Some Oracle example - replace to_date() with eqivalent:

  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 dual table:

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

Upvotes: -1

Taryn
Taryn

Reputation: 247810

Using the formula from @Mikeal Eriksson's answer here.

I would convert the float to a bigint and then create the datetime:

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

See SQL Fiddle with Demo

Upvotes: 11

Related Questions