Skip to main content

Utility method for converting Unix epoch seconds to DateTime structure.

internal static readonly DateTime EPOCH_START = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

/// <summary>
/// Utility method for converting Unix epoch seconds to DateTime structure.
/// </summary>
/// <param name="seconds">The number of seconds since January 1, 1970.</param>
/// <returns>Converted DateTime structure</returns>
public static DateTime ConvertFromUnixEpochSeconds(int seconds)
{
    return new DateTime(seconds * 10000000L + EPOCH_START.Ticks, DateTimeKind.Utc).ToLocalTime();
}

public static int ConvertToUnixEpochSeconds(DateTime dateTime)
{
    return (int)ConvertToUnixEpochMilliSeconds(dateTime);
}

public static double ConvertToUnixEpochMilliSeconds(DateTime dateTime)
{
    TimeSpan ts = new TimeSpan(dateTime.ToUniversalTime().Ticks - EPOCH_START.Ticks);
    double milli = Math.Round(ts.TotalMilliseconds, 0) / 1000.0;
    return milli;
}