Search code examples
sql-servert-sqlunix-timestamp

How to convert Unix time in microseconds with SQL Server?


I've seen a lot on converting Unix time from other formats to datetime, but nothing really from microseconds. How can you SELECT a field this with a timestamp of 1470562081943371 without getting overflows with an output of YYYY-MM-DD HH:MM:SS:MM?


Solution

  • Not sure if this is unit is correct, but...

    Declare @UnixTime bigint = 1470562081943371
    Select DateAdd(MS,round(((@UnixTime/1000000.)-(@UnixTime/1000000))*1000,0),DateAdd(SECOND,(@UnixTime/1000000),'1970-01-01 00:00:00'))
    

    Returns

    2016-08-07 09:28:01.943
    

    Confirmed results with http://www.epochconverter.com/

    enter image description here