Tuesday 1 July 2008

How do I convert a Unix timestamp into a DateTime object in C#.NET?

Unix time, or POSIX time, is the number of seconds elapsed since midnight of January 1, 1970 (UTC).

Here is a utility class that can be used to convert a Unix timestamp into a DateTime object and vice versa:

using System;

public static class DateTimeUtility
{
public static DateTime UnixOrigin
{
get { return new DateTime( 1970, 1, 1, 0, 0, 0, 0 ); }
}

public static DateTime ConvertFromUnixTimestamp( long timestamp )
{
return UnixOrigin.AddSeconds( (long)timestamp );
}

public static long ConvertToUnixTimestamp( DateTime dateTime )
{
TimeSpan differnce = dateTime - UnixOrigin;

return (long)differnce.TotalSeconds;
}
}

No comments: