Unix Time and .NET DateTime

I’m working on a ASP.NET project where I need to interface with a MySQL database that’s populated by a PHP application. Naturally, all references to time are in Unix timestamps, and also quite naturally, .NET’s DateTime type doesn’t have any Unix-related methods. Thankfully, it’s easy enough to convert between the two.

A Unix timestamp is the amount of seconds elapsed since January 1, 1970 (called the Unix Epoch). Knowing this, you can write a couple of methods to convert .NET DateTime to Unix timestamps and vice-versa. The following is a little class I wrote for my project.

public static class DateTimeUtils
{
    private static DateTime _Epoch;

    static DateTimeUtils()
    {
        _Epoch = new System.DateTime(1970, 1, 1, 0, 0, 0);
    }

    public static double ToUnixTimeStamp(DateTime dateTime)
    {
        TimeSpan timeSpan = dateTime - _Epoch;

        return Math.Floor(timeSpan.TotalSeconds);
    }

    public static DateTime FromUnixTimeStamp(double timestamp)
    {
        return _Epoch.AddSeconds(timestamp);     
    }
}

The ToUnixTimeStamp() method returns whole seconds. So slight modifications are needed if you want a timestamp with milliseconds.

12/1/2008 10:34:01 AM | Tags: C#, .NET, ASP.NET
© 2008 Jeremy McPeak