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

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

    The latest version of .NET (v4.6) has added built-in support for Unix time conversions. That includes both to and from Unix time represented by either seconds or milliseconds.

    • Unix time in seconds to UTC DateTimeOffset:

    DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
    
    • DateTimeOffset to Unix time in seconds:

    long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
    
    • Unix time in milliseconds to UTC DateTimeOffset:

    DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(1000000);
    
    • DateTimeOffset to Unix time in milliseconds:

    long unixTimeStampInMilliseconds = dateTimeOffset.ToUnixTimeMilliseconds();
    

    Note: These methods convert to and from a UTC DateTimeOffset. To get a DateTime representation simply use the DateTimeOffset.UtcDateTime or DateTimeOffset.LocalDateTime properties:

    DateTime dateTime = dateTimeOffset.UtcDateTime;
    

提交回复
热议问题