至高吴上(Alfa.wu)

一个人,一生,能坚持做好一件事情是多么的牛XX啊!!!

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

以下方法全部摘自网络,供自己备查使用,如有侵犯您的版权请告知,尽快删除!谢谢!

推荐方法:

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.        }

 

 

 

 

 

 

posted on 2012-11-21 09:17  Alfa  阅读(8134)  评论(0编辑  收藏  举报