本文介绍了如何将byte []转换为datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在读取当前DateTime到字节数组如何将字节数组转换回DateTime?



我尝试过:



Hi i am reading the current DateTime to byte array how to convert the byte array back to DateTime ?

What I have tried:

public static byte ConvertToBcd(byte x)
{

    int msb = x / 10;

    int lsb = x - (msb * 10);

    msb = msb << 4;

    return (byte)(msb | lsb);

}


public static byte[] GetLocalTimeInBCD()
{

    DateTime now = DateTime.Now;

    byte[] Data = new byte[4];

    Data[0] = (byte)(now.Year - 100);

    Data[1] = (byte)now.Month;

    Data[2] = (byte)now.Day;

    Data[3] = (byte)now.Hour;


    for (int i = 0; i < 4; i++)
    {

        Data[i] = ConvertToBcd(Data[i]);

    }

    return Data;

}

推荐答案

public static byte ConvertFromBcd(byte bcd)
 {
   return (byte) ((bcd >> 4) * 10 + (bcd & 0XF));
 }


//Convert DateTime to bytes (always convert datetime to ticks)
byte[] byteValue = BitConverter.GetBytes(DateTime.Now.Ticks);
//Convert datetime to longvalue
long longVar = BitConverter.ToInt64(byteValue, 0);
//Convert to datetime.
DateTime dateTimeVar = new DateTime(longVar);


这篇关于如何将byte []转换为datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:01
查看更多