Convert .NET Ticks to SQL Server DateTime

后端 未结 7 906
攒了一身酷
攒了一身酷 2020-11-30 10:10

I am saving a TimeSpan (from .NET) value in my db as BIGINT in SQL Server (saving the Ticks property). I want to know how to convert this BIG

7条回答
  •  生来不讨喜
    2020-11-30 11:05

    You can use this function taken from Pavel Gatilov's blog to convert a 64-bit integer to a datetime value with millisecond precision in server local time:

    CREATE FUNCTION NetFxUtcTicksToDateTime
    (
       @Ticks bigint
    )
    RETURNS datetime
    AS
    BEGIN
    
    -- First, we will convert the ticks into a datetime value with UTC time
    DECLARE @BaseDate datetime;
    SET @BaseDate = '01/01/1900';
    
    DECLARE @NetFxTicksFromBaseDate bigint;
    SET @NetFxTicksFromBaseDate = @Ticks - 599266080000000000;
    -- The numeric constant is the number of .Net Ticks between the System.DateTime.MinValue (01/01/0001) and the SQL Server datetime base date (01/01/1900)
    
    DECLARE @DaysFromBaseDate int;
    SET @DaysFromBaseDate = @NetFxTicksFromBaseDate / 864000000000;
    -- The numeric constant is the number of .Net Ticks in a single day.
    
    DECLARE @TimeOfDayInTicks bigint;
    SET @TimeOfDayInTicks = @NetFxTicksFromBaseDate - @DaysFromBaseDate * 864000000000;
    
    DECLARE @TimeOfDayInMilliseconds int;
    SET @TimeOfDayInMilliseconds = @TimeOfDayInTicks / 10000;
    -- A Tick equals to 100 nanoseconds which is 0.0001 milliseconds
    
    DECLARE @UtcDate datetime;
    SET @UtcDate = DATEADD(ms, @TimeOfDayInMilliseconds, DATEADD(d, @DaysFromBaseDate, @BaseDate));
    -- The @UtcDate is already useful. If you need the time in UTC, just return this value.
    
    -- Now, some magic to get the local time
    RETURN @UtcDate + GETDATE() - GETUTCDATE();
    END
    GO
    

    Alternative code suitable for inline usage:

    DECLARE @Ticks bigint
    set @Ticks = 634899090000000000
    select DATEADD(ms, ((@Ticks - 599266080000000000) - 
       FLOOR((@Ticks - 599266080000000000) / 864000000000) * 864000000000) / 10000,
       DATEADD(d, (@Ticks - 599266080000000000) / 864000000000, '01/01/1900')) +
       GETDATE() - GETUTCDATE()
    

提交回复
热议问题