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#<
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;
}