【问题标题】:6 bytes timestamp to DateTimeDateTime 的 6 字节时间戳
【发布时间】:2012-04-11 14:09:42
【问题描述】:

我使用 3rd 方 API。根据其规范如下

  byte[] timestamp = new byte[] {185, 253, 177, 161, 51, 1}

表示从 1970 年 1 月 1 日开始的毫秒数 为传输而生成

问题是我不知道如何将它翻译成 DateTime。

我试过了

DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long milliseconds = BitConverter.ToUInt32(timestamp, 0);
var result =  Epoch + TimeSpan.FromMilliseconds(milliseconds);

结果是 {2/1/1970 12:00:00 AM},但预计是 2012 年。

【问题讨论】:

  • timestamp 是使用小端还是原生端?
  • 所有数据都使用little-endian字节序。
  • 预期的结果真的是2012年吗?我得到14.11.2011 10:49:16
  • 您正在使用 BitConverter.ToUInt32() 这肯定不会有帮助...只会查看字节 [0...3](即 32 位)
  • 这个 API 如何处理纪元开始之前的日期?它是否将最后一个字节的 MSB 作为符号位线程化?还是它根本不支持这样的日期?

标签: c# datetime


【解决方案1】:
        byte[] timestamp = new byte[] { 185, 253, 177, 161, 51, 1, 0, 0, };
        DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        ulong milliseconds = BitConverter.ToUInt64(timestamp, 0);
        var result = Epoch + TimeSpan.FromMilliseconds(milliseconds);

结果是 2011 年 11 月 14 日

为 CodeInChaos 添加特殊的填充代码:

    byte[] oldStamp = new byte[] { 185, 253, 177, 161, 51, 1 };
    byte[] newStamp = new byte[sizeof(UInt64)];
    Array.Copy(oldStamp, newStamp, oldStamp.Length);

用于在大端机器上运行:

if (!BitConverter.IsLittleEndian)
{
    newStamp = newStamp.Reverse().ToArray();
}

【讨论】:

  • 不符合更新后的问题。您还应该包含添加填充的代码。
  • 现在您的代码在大端系统上根本不起作用,因为您的解析假定为原生端,而填充假定为小端。
  • 是的,这正是您使用 BitConverter.ToUInt64 被破坏的原因,因为它假定本机字节序。
  • 如果在大端机器上运行,您可以反转输入数据。看我的编辑。但我认为OP可以手动做这些事情
  • 这不是很 C#-ish 但你可以做 Array.Resize(ref timestamp, 8) 来填充原始字节数组。
【解决方案2】:

我假设timestamp 使用小端格式。我也省略了参数验证。

long GetLongLE(byte[] buffer,int startIndex,int count)
{
  long result=0;
  long multiplier=1;
  for(int i=0;i<count;i++)
  {
    result += buffer[startIndex+i]*multiplier;
    multiplier *= 256;
  }
  return result;
}

long milliseconds = GetLongLE(timestamp, 0, 6);

【讨论】:

  • 有个东西叫BitConverter.ToInt64
  • @atornblad 1) 你需要填充数组。 2) BitConverter.ToInt64 使用本地字节序。我假设他收到的数据是小端的。
猜你喜欢
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
  • 2010-12-18
  • 2012-08-15
  • 1970-01-01
  • 1970-01-01
  • 2022-01-24
  • 2016-07-10
相关资源
最近更新 更多