Unix Epoch time to a System.DateTime value

A quick "how to" on converting a Unix Epoch time value to a .net DateTime value.
Email Image
kick it on DotNetKicks.com
Unix Epoch time

Times in Unix are stored as a number of seconds after the 1st January 1970 00:00:00.

Therefore to convert a Unix Epoch time to a .net DateTime value, we need to instantiate a DateTime of the Unix Epoch and add the number of seconds.

public DateTime UnixEpochTimeToDateTime(double epochTimeStamp)
{
    // Instantiate a DateTime equivalent to the UNIX Epoch (1st Jan 1970 00:00:00)
    // and add the required number of seconds.
    return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epochTimeStamp).ToLocalTime();
}
public double DateTimeToUnixEpochTime(DateTime dateTime)
{
    // Calculate the difference between the supplied DateTime and the Unix Epoch minimum value.
    TimeSpan timeDifference = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

    // Return the difference in seconds, rounding to the lowest.
    return Math.Floor(timeDifference.TotalSeconds);
}

This article was published on the 18th April 2008