如何将Byte数组转换为毫秒级Unix时间戳并得到对应DateTime?
错误原因
- 第一个直接报错原因:
BitConverter.ToInt64()方法要求从指定偏移量开始读取8个字节来转换为long类型,你当前的字节缓冲区只有6个字节,长度不足触发了参数异常。 - 第二个隐藏错误:你现有的
unixTimeStampToDateTime方法用的是AddSeconds()处理时间戳,但你明确说明存储的是毫秒级Unix时间戳,直接传入毫秒值会导致日期结果完全不符合预期。
解决逻辑
你提供的6字节是大端序排列的48位毫秒时间戳,对应十进制值为1590734700000,刚好匹配你期望的2020-05-29 14:45(东八区本地时间),只需要先把6字节补位到8字节兼容long类型的转换要求,再修改时间戳转换方法适配毫秒单位即可。
可运行示例代码
// 原字节缓冲区 byte[] buffer = new byte[] { 0x01, 0x72, 0x60, 0x77, 0x59, 0x80 }; // 1. 6字节大端时间戳转long类型 // 补2个高位0,拼成8字节大端数组 byte[] longBuffer = new byte[8]; Buffer.BlockCopy(buffer, 0, longBuffer, 2, 6); // 兼容系统字节序:如果当前系统是小端序,反转数组后再转换 if (BitConverter.IsLittleEndian) { Array.Reverse(longBuffer); } long timestamp = BitConverter.ToInt64(longBuffer, 0); // 2. 毫秒级Unix时间戳转DateTime方法 DateTime UnixMillisecondTimestampToDateTime(long unixMillisecondTimestamp) { DateTime dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); dtDateTime = dtDateTime.AddMilliseconds(unixMillisecondTimestamp).ToLocalTime(); return dtDateTime; } // 转换结果就是你期望的 05/29/2020 14:45 var result = UnixMillisecondTimestampToDateTime(timestamp);
内容的提问来源于stack exchange,提问作者Aaron Parrilla
相关产品推荐
相关产品推荐

