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

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

    Be careful, if you need precision higher than milliseconds!

    .NET (v4.6) methods (e.g. FromUnixTimeMilliseconds) don't provide this precision.

    AddSeconds and AddMilliseconds also cut off the microseconds in the double.

    These versions have high precision:

    Unix -> DateTime

    public static DateTime UnixTimestampToDateTime(double unixTime)
    {
        DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        long unixTimeStampInTicks = (long) (unixTime * TimeSpan.TicksPerSecond);
        return new DateTime(unixStart.Ticks + unixTimeStampInTicks, System.DateTimeKind.Utc);
    }
    

    DateTime -> Unix

    public static double DateTimeToUnixTimestamp(DateTime dateTime)
    {
        DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
        long unixTimeStampInTicks = (dateTime.ToUniversalTime() - unixStart).Ticks;
        return (double) unixTimeStampInTicks / TimeSpan.TicksPerSecond;
    }
    

提交回复
热议问题