Web Design that taps into the haromny and vision of your dreams.

Converting To and From Unix Timestamps

By on in Coding

139 words, estimated reading time 1 minutes.

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.

Last updated on: Wednesday 21st June 2017



Have a question or suggestion? Please leave a comment to start the discussion.


Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.