用了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"));