如何将byte []转换为datetime [英] How to convert byte[] to datetime

查看:115
本文介绍了如何将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;

}

推荐答案

那么你只需要恢复这个过程。开始于

Well you have just to revert the process. Start with
public static byte ConvertFromBcd(byte bcd)
 {
   return (byte) ((bcd >> 4) * 10 + (bcd & 0XF));
 }


FromBinary方法采用使用ToBinary方法创建的long值。它包含Kind和Ticks组件,这不是数据库时间戳包含的内容。



使用BitConverter获取长值是正确的,但是你必须采取时间戳的时间原点并将长值添加为正确的单位。假设它是来自MySQL数据库的时间戳,IIRC是1980-01-01的毫秒数:



The FromBinary method takes a long value that is created using the ToBinary method. It contains the Kind and Ticks components, and this is not what a database timestamp contains.

Using BitConverter to get the long value is correct, but then you have to take the time origin for the time stamp and add the long value as the correct unit. Assuming it's a timestamp from a MySQL database, IIRC it's the number of milliseconds from 1980-01-01:

//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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆