• 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.        }
  • 相关阅读:
    序列化二叉树
    按之字形顺序打印二叉树
    C#读写文件的方法汇总_C#教程_脚本之家
    c#缓存介绍(转)
    ASP.NET 缓存技术分析
    pickle使用
    python3.4使用文件
    io的常用操作
    manven需要注意点几点
    git中一些常用的命令
  • 原文地址:https://www.cnblogs.com/wuyifu/p/2780118.html
Copyright © 2020-2023  润新知