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

by Colin Cochrane 3/7/2008 7:58:00 PM

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!

Tags: , ,

Visual Basic | Code Tips | C#

Comments (2) -

6/9/2008 11:59:18 PM

Can you tell me

PHP $Microtime(true) equivalent in ASP.NET.
$Microtime - Unix timestamp with milliseconds.
Please send it on my email.

Thanks in advance

Sanoj Kumar India

9/22/2009 10:42:31 AM

Sounds easy when someone else talks about it Laughing

thx

Dejan United States

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Powered by BlogEngine.NET 2.5.0.6

All Content and Intellectual Property is under Copyright Protection | Colin Cochrane ©2007

About the author

Colin Cochrane

Colin Cochrane

SEO and ASP.NET Developer.

Recent comments

Archive

Authors

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer. © Copyright Colin Cochrane 2012

Sign in