How can I convert a Unix timestamp to DateTime and vice versa?

前端 未结 19 2477
抹茶落季
抹茶落季 2020-11-21 06:37

There is this example code, but then it starts talking about millisecond / nanosecond problems.

The same question is on MSDN, Seconds since the Unix epoch in C#<

19条回答
  •  终归单人心
    2020-11-21 06:55

    I needed to convert a timeval struct (seconds, microseconds) containing UNIX time to DateTime without losing precision and haven't found an answer here so I thought I just might add mine:

    DateTime _epochTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    private DateTime UnixTimeToDateTime(Timeval unixTime)
    {
        return _epochTime.AddTicks(
            unixTime.Seconds * TimeSpan.TicksPerSecond +
            unixTime.Microseconds * TimeSpan.TicksPerMillisecond/1000);
    }
    

提交回复
热议问题