Converting To and From Unix Timestamps with C#

Last Updated January 7, 2019 by . First Published in 2010.

Converting To and From Unix Timestamps with C#

From time to time it's necessary to convert Unix timestamps. These C# methods will do just that and make interacting with Unix easy.

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.

C#
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.

Was this article helpful to you?
 
Comments

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

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.