【问题标题】:From Byte[] to unixTimestamp in miliseconds从 Byte[] 到 unix Timestamp(以毫秒为单位)
【发布时间】:2021-09-30 15:16:45
【问题描述】:

我有一个像这样的简单缓冲区:

Byte[] buffer = new byte[] { 0x01, 0x72, 0x60, 0x77, 0x59, 0x80};

我需要从这个值中获取日期(它的单位是 Unix timeStamp 毫秒)

所以我尝试转换为 long,然后传递给我发现从 long 转换为 dateTime 的函数,如下所示:

public static DateTime unixTimeStampToDateTime(long unixTimeStamp)
{
    // Unix timestamp is seconds past epoch
    DateTime  dtDateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    dtDateTime = dtDateTime.AddSeconds(unixTimeStamp).ToLocalTime();
    return dtDateTime;
}

我尝试像这样从数组中获取长值:

    long timestamp = BitConverter.ToInt64(buffer,0);

但我收到此错误:

System.ArgumentException: 'Destination array is not long enough to copy all the items in the collection. Check array index and length. '

我在这里缺少什么?提前致谢。

编辑 转换后的预期值为:05/29/2020 14:45

【问题讨论】:

  • 将整数表示为 6 个字节是不常见的。它总是六个字节吗?什么是字节序? (您可以指出我们的任何规范吗?)
  • @JonSkeet 遗憾的是,不,我认为我可以处理的字节顺序,如果有的话,根据文档,转换为 dateTime 后的预期结果应该是 05/29/2020 14:45,是的,它总是六个字节
  • 添加到@jonskeet 所说的内容...您希望缓冲区转换为什么值?那 6 个字节是从哪里来的?
  • "根据文档" - 哪个文档?只需知道这些字节的来源就可能在这里产生重大影响。

标签: c# datetime datetime-format asp.net-core-3.1


【解决方案1】:

您可以尝试在 Linq 的帮助下 Aggregate 数组的项目以获得 Int64 值:

  using System.Linq;

  ... 

  byte[] buffer = new byte[] { 0x01, 0x72, 0x60, 0x77, 0x59, 0x80 };

  ...

  long shift = buffer.Aggregate(0L, (s, a) => s * 256 + a);

  DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(shift);

  Console.WriteLine($"{result:d MMMM yyyy HH:mm:ss}");

结果:

  29 May 2020 12:45:33

如您所见,时间是12:45,而不是14:45,所以您可能想要处理DateTimeKind.Utc 片段。如果buffer 代表本地时间,而不是UTC:

  DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(shift);

如果buffer 代表 UTC,但您想要 本地 时间:

  DateTime result = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(shift);

  result = result.ToLocalTime();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 1970-01-01
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多