从 Byte[] 到 unix 时间戳(以毫秒为单位)
From Byte[] to unixTimestamp in miliseconds
我有一个像这样的简单缓冲区:
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
您可以在 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
表示local时间,不是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();
我有一个像这样的简单缓冲区:
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
您可以在 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
表示local时间,不是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();