C# 將時間戳 byte[] 轉換成 datetime 的幾個方法


以下方法全部摘自網絡,供自己備查使用,如有侵犯您的版權請告知,盡快刪除!謝謝!

推薦方法:

DateTime now = DateTime.Now;

byte[] bts = BitConverter.GetBytes(now.ToBinary());
DateTime rt = DateTime.FromBinary(BitConverter.ToInt64(bts, 0)); 

 

 

 

用了2個byte,日期范圍 2000-01-01 ~ 2127-12-31,下面是轉換方法: 
        // Date -> byte[2] 
        public static byte[] DateToByte(DateTime date) 
        { 
            int year = date.Year - 2000; 
            if (year < 0 || year > 127) 
                return new byte[4]; 
            int month = date.Month; 
            int day = date.Day; 
            int date10 = year * 512 + month * 32 + day; 
            return BitConverter.GetBytes((ushort)date10); 
        } 
        // byte[2] -> Date 
        public static DateTime ByteToDate(byte[] b) 
        { 
            int date10 = (int)BitConverter.ToUInt16(b, 0); 
            int year = date10 / 512 + 2000; 
            int month = date10 % 512 / 32; 
            int day = date10 % 512 % 32; 
            return new DateTime(year, month, day); 
        } 
調用舉例: 
            byte[] write = DateToByte(DateTime.Now.Date); 
            MessageBox.Show(ByteToDate(write).ToString("yyyy-MM-dd"));

 

 

 

 

 

1./// <summary> 2.        /// 將BYTE數組轉換為DATETIME類型 3.        /// </summary> 4.        /// <param name="bytes"></param> 5.        /// <returns></returns> 6.        private DateTime BytesToDateTime(byte[] bytes)
7.        {
8.            if (bytes != null && bytes.Length >= 5)
9.            {
10.                int year = 2000 + Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[0] }, 0));
11.                int month = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[1] }, 0));
12.                int date = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[2] }, 0));
13.                int hour = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[3] }, 0));
14.                int minute = Convert.ToInt32(BitConverter.ToString(new byte[1] { bytes[4] }, 0));
15.                DateTime dt = new DateTime(year, month, date, hour, minute, 0);
16.                return dt;
17.            }
18.            else19.            {
20.                return new DateTime();
21.            }
22.        }

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM