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

前端 未结 19 2421
抹茶落季
抹茶落季 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:52

    To supplement ScottCher's answer, I recently found myself in the annoying scenario of having both seconds and milliseconds UNIX timestamps arbitrarily mixed together in an input data set. The following code seems to handle this well:

    static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    static readonly double MaxUnixSeconds = (DateTime.MaxValue - UnixEpoch).TotalSeconds;
    
    public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
    {
       return unixTimeStamp > MaxUnixSeconds
          ? UnixEpoch.AddMilliseconds(unixTimeStamp)
          : UnixEpoch.AddSeconds(unixTimeStamp);
    }
    

提交回复
热议问题