본문 바로가기

컴퓨터/SQL Server

Datetime to Binary in C# (CLR Function)

** 추후 내용 추가 예정      



SQL Server에서 CLR 함수를 호출해 DateTime으로 선언된 인자에 같은 datetime 타입의 값을 전달해도

C#에서 인자로 받은 datetime 값을 ToBinary() 함수를 통해 binary 값을 얻은 것과 

SQL Server에서 datetime 값을 varbinary로 변환했을 때의 값이 다르게 나왔다.

그래서 검색을 해보았더니 다음과 같은 연산을 사용하면 SQL Server에서의 형변환 값과 C# 에서의 형변환 값이 같게 나온다는 것을 알게 되었고 적용해본 결과 실제로 값이 같게 나오는 것을 확인했다.



[ Datimetime to Binary]


public static byte[] datetime2binary(DateTime indata)

    {

      byte[] tmpdata = new byte[8];

      byte[] days = new byte[4];

      byte[] milliseconds = new byte[4];

      //string hex;


      TimeSpan s = new TimeSpan(indata.ToFileTime() - new DateTime(1900, 1, 1, 0, 0, 0).ToFileTime());


      if (indata.Year < 1900)

      {

        days = System.BitConverter.GetBytes(s.Days-1);

        DateTime test = new DateTime(1900, 1, 1, indata.Hour, indata.Minute, indata.Second, indata.Millisecond);

        TimeSpan s2 = new TimeSpan(test.ToFileTime() - new DateTime(1900, 1, 1, 0, 0, 0).ToFileTime());


        s2 = s2.Subtract(new TimeSpan(s2.Days, 0, 0, 0, 0));

        milliseconds = System.BitConverter.GetBytes(Convert.ToInt32(s2.TotalMilliseconds / 3.3333333));

      }

      else

      {

        days = System.BitConverter.GetBytes(s.Days);

        s = s.Subtract(new TimeSpan(s.Days, 0, 0, 0, 0));

        milliseconds = System.BitConverter.GetBytes(Convert.ToInt32(s.TotalMilliseconds / 3.3333333));

      }


      if (BitConverter.IsLittleEndian)

      {

        Array.Reverse(days);

        Array.Reverse(milliseconds);

      }


      tmpdata[0] = days[0];

      tmpdata[1] = days[1];

      tmpdata[2] = days[2];

      tmpdata[3] = days[3];

      tmpdata[4] = milliseconds[0];

      tmpdata[5] = milliseconds[1];

      tmpdata[6] = milliseconds[2];

      tmpdata[7] = milliseconds[3];

      

      //hex = BitConverter.ToString(tmpdata);

}


--> 주석을 풀고 hex 에 담긴 값을 출력하면 tmpdata에 저장된 HEX 값을 볼 수 있다.




[Binary to Datetime]


 public static DateTime binary2datetime(byte[] indata)

    {

      byte[] days = new byte[4];

      byte[] time = new byte[4];


      Buffer.BlockCopy(indata, 0, days, 0, 4);

      Buffer.BlockCopy(indata, 4, time, 0, 4);


      if (BitConverter.IsLittleEndian)

      {

        Array.Reverse(days);

        Array.Reverse(time);

      }


      DateTime dt = new DateTime(1900, 1, 1, 0, 0, 0);

      DateTime test = new DateTime(1, 1, 1, 0, 0, 0);


      dt = dt.AddDays((double)BitConverter.ToInt32(days,0));

      dt = dt.AddMilliseconds((double)(BitConverter.ToInt32(time, 0) * 3.3333333));


      return dt;

    }



'컴퓨터 > SQL Server' 카테고리의 다른 글

BLOB  (0) 2015.09.30
SQL Data type VS C# Data type  (0) 2015.09.22
SQL Server 형변환  (0) 2015.09.09
MSSQL Msg 10327 해결방법  (0) 2015.06.01
MSSQL 계산열  (0) 2014.12.10