Colin Cochrane

Colin Cochrane is a Software Developer based in Victoria, BC specializing in C#, PowerShell, Web Development and DevOps.

.NET Code Tips: Converting A UNIX Timestamp To System.DateTime

After having to deal with UNIX timestamps in an application I am currently developing, I realized that there's probably a few people out there who are wondering how to convert a UNIX timestamp into a useable System.DateTime in a .NET application. 

Well the good news is that it's quite simple.  All a UNIX timestamp represents is the number of seconds since January 1st, 1970 12:00:00 AM.  So all we have to do is create a new System.DateTime structure, set it to 1/1/1970 12:00:00 AM, and use the AddSeconds() methods to tack on the timestamp.

Visual Basic:

   1: Function ConvertTimestamp(ByVal timestamp as Double) As DateTime
   2:     Return New DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp)
   3: End Function

C#:

   1: static DateTime ConvertTimestamp(double timestamp)
   2: {
   3:   return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp);
   4: }

 

Keep in mind that this method will return the time as Coordinated Univeral Time (UTC), so if you want to convert the value to local time you can simply modify the procedure as follows:

Visual Basic:

   1: Function ConvertTimestamp(ByVal timestamp as Double) As DateTime
   2:     Return New DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp).ToLocalTime()
   3: End Function

C#:

   1: static DateTime ConvertTimestamp(double timestamp)
   2: {
   3:   return new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(timestamp).ToLocalTime();
   4: }

It's that easy to turn a UNIX timestamp into a .NET System.DateTime object. 

Happy coding!