Convert Unix Time from/to System.DateTime

A pair of simple methods for working with Unix time in .NET. The code uses a 64 bit integer datatype so is not affected by 2038 problem.

static class DateTimeExtensions  
{
    static readonly DateTime BeginningOfUnixTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static DateTime FromUnix(long unixTime)
    {
        return BeginningOfUnixTime.AddSeconds(unixTime).ToLocalTime();
    }

    public static long ToUnix(this DateTime dt)
    {
        return (long)((dt.ToUniversalTime() - BeginningOfUnixTime).TotalSeconds);
    }
}
Google
m@kli.dk @klinkby RSS feed  GitHub