来自TickCount的日期时间?

Alp*_*pha 1 c# datetime

我正在C#程序中捕获一些事件,这些事件以时间戳作为系统tickcount(自启动时间以来的毫秒)返回.

根据我看到的其他问题,我知道我可以从System.Environment.TickCount属性(或其他东西)获得相同的数字,如何推断出与我收到的TickCount相对应的DateTime对象?

Jon*_*eet 6

如果没有更多信息,你就不可能(即便如此,它也可能含糊不清).Environment.TickCount收益:

一个32位有符号整数,包含自上次启动计算机以来经过的时间量(以毫秒为单位).

...所以,除非你能从某个地方找到计算机启动的时间,否则你运气不好.您可以使用注册表项或系统调用来查找上次启动时间,但我不了解它们.当然,您可以通过自己和尽可能快地(或之前)获得近似值,并找出两者之间的差异:Environment.TickCountDateTime.UtcNow

public static DateTime UnreliableDateTimeFromTickCount(int tickCount)
{
    DateTime now = DateTime.UtcNow;
    DateTime boot = now - TimeSpan.FromMilliseconds(Environment.TickCount);
    return boot + TimeSpan.FromMilliseconds(tickCount);
}
Run Code Online (Sandbox Code Playgroud)

然而,即使那个,这个值周期轮的每一个24.9天,所以如果电脑已经上都比较长,计数是模糊的.

我建议Environment.TickCount尽可能避免使用,基本上 - 这是否在你的控制之下?