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#<
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.
DateTimeOffset
:DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeSeconds(1000);
DateTimeOffset
to Unix time in seconds:long unixTimeStampInSeconds = dateTimeOffset.ToUnixTimeSeconds();
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;