hikoruKazuto
hikoruKazuto

Reputation: 23

Convert hex value from SQL Server to datetime in C#

I need to convert 8 bytes from a hexadecimal value to a new datetime in C#. The function should do the same as it does in SQL Server.

I have the hexadecimal value as a string "0000AC0500000000" or a list of bytes:

["0", "0", "172", "5", "0", "0", "0", " 0 ",]

From that I need to obtain the date "2020-07-27 00:00:00:000". The convert of the SQL Server works perfectly to recover up to milliseconds with only 8 bytes. As shown convert function in SQL Server

Upvotes: 1

Views: 391

Answers (1)

jdweng
jdweng

Reputation: 34427

Use following

            string input = "0000AC0500000000";

            int daysFrom1900 = int.Parse(input.Substring(0,8),NumberStyles.HexNumber);
            int ticksFromMidnight = int.Parse(input.Substring(8), NumberStyles.HexNumber);
            DateTime year1900 = new DateTime(1900, 1, 1);
            DateTime date = year1900.AddDays(daysFrom1900).AddTicks(ticksFromMidnight*(10/3.0));

Upvotes: 1

Related Questions