C# Extension Methods

Just a quick post.. thought I’d share a neat way of handling some legacy date nastyness from an oracle DB that I’m having to interface with.

DateTime’s on this monstrosity of the 90’s are stored as the typical Unix Epoch format, as in seconds since 1/1/1970. The usual method of handling these things is to have some conversion functions in a utility namespace somewhere that handles the (quite simple) translation to and from the C# DateTime format.

However, using new fangled features makes for some really neat code by ‘extending’ framework types to convert to and from the Unix times.  Anyway, enough talk, show me the code 😉

public static class ExtensionMethods
{
    /// <summary>
    /// Long extension method to convert a Unix epoch 
    /// time to a standard C# DateTime object.
    /// </summary>
    /// <returns>A DateTime object representing the unix 
    /// time as seconds since 1/1/1970</returns>
    public static DateTime FromEpoch(this long unixTime) {
        return new DateTime(1970, 1, 1).AddSeconds(unixTime);
    }
    /// <summary>
    /// Date Time extension method to return a unix epoch 
    /// time as a long
    /// </summary>
    /// <returns> A long representing the Date Time as the number 
    /// of seconds since 1/1/1970</returns>
    public static long ToEpoch(this DateTime dt) {
        return (long)(dt - new DateTime(1970, 1, 1)).TotalSeconds;
    }
}

So , now instead feeling all dirty inside, riddled with guilt at calling those filthy Utility.Methods() you can ease your conscience by using

DateTime dt1 = DateTime.Now;

long unix1 = dt1.ToEpoch();

DateTime dt2 = unix1.FromEpoch();

Ahh, extension method bliss, and once again all is well in the world.

My work here is done.

For today.

😉

Download the sample

This entry was posted in General. Bookmark the permalink.

Leave a Reply