Convert SQL Server DateTime object to BIGINT (.Net ticks)

前端 未结 8 1273
执念已碎
执念已碎 2020-12-08 21:38

I need to convert a DateTime type value to BIGINT type in .Net ticks format (number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001).<

相关标签:
8条回答
  • 2020-12-08 22:12

    EDIT: Updated due to updated details regarding original question

    To give such precision of 100ns you should execute algorithm on SQL Server 2008 using new date type - datetime2 which accuracy is 100 nanoseconds. Obviously link to an algorithm itself already provided in an other post.

    DateTime.Ticks Property

    A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

    The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue. It does not include the number of ticks that are attributable to leap seconds.

    DateTime dateTime = DateTime.Now;
    System.Int64 ticks = dateTime.Ticks;
    
    0 讨论(0)
  • 2020-12-08 22:15

    A more performant solution might be: (note first two line are just for testing)

    DECLARE @YourDate DATETIME
    
    SET @YourDate = GETDATE()
    
    SELECT 
    (
      (
      -- seconds since 1970
      CAST(DATEDIFF(s,'1970-01-01 12:00:00',@YourDate) As BIGINT)
      )
    -- seconds from 0001 to 1970 (approximate)
    + 62125920000
    ) 
    -- make those seconds nanoseconds
    * 1000000000
    

    Given that your input date only goes down to seconds we just work it out in seconds and multiply by 1000000000 to get nanoseconds.

    0 讨论(0)
提交回复
热议问题