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

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

    DateTime to UNIX timestamp:

    public static double DateTimeToUnixTimestamp(DateTime dateTime)
    {
        return (TimeZoneInfo.ConvertTimeToUtc(dateTime) - 
               new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc)).TotalSeconds;
    }
    

提交回复
热议问题