4

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?

Justin Pihony
  • 66,056
  • 18
  • 147
  • 180
Luke Belbina
  • 5,708
  • 12
  • 52
  • 75

2 Answers2

11

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

Community
  • 1
  • 1
Taryn
  • 242,637
  • 56
  • 362
  • 405
-1

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
Art
  • 5,616
  • 1
  • 20
  • 22