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

前端 未结 19 2505
抹茶落季
抹茶落季 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条回答
  •  猫巷女王i
    2020-11-21 06:56

    DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
    DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);
    

    Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

    To go the other way:

    double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;
    

    Truncate to Int64 and/or use TotalSeconds as needed.

提交回复
热议问题