Learning never exhausts the mind
Home >  Coding > C# ASP.Net MVC > Converting To and From Unix Timestamps

Last Updated on by

From time to time it is necessary to convert to and from Unix timestamps, mainly when dealing with system interoperability. These timestamps are an accurate measure of time from a given point and have a simple data type.

Unix time is defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970.

These two functions will convert a .Net DateTime into a Unix timestamp and vice versa.

public static DateTime ConvertFromUnixTimestamp(ulong timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime? date = null)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    TimeSpan diff = (date ?? DateTime.Now) - origin;
    return Convert.ToDouble(Math.Floor(diff.TotalSeconds));
}

Year 2038 Problem

There are however limitations to the current implementation of Unix timestamps. On 32-bit data types, the date time 03:14:07 UTC on 19 January 2038 represents the maximum value an integer can hold. One second after this and the time will rollover, back to 1970. This is the second coming of the millennium bug. Hopefully, by then, every system will have been upgraded to 64-bit long data types.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.