Object - ToNullableDateTimeOffSet

An object extension method that converts the @this to a nullable date time off set.

Try it

public static void Main()
{
    object[] values = { 16352, null, "monthly", "05/01/1996", "Tue Apr 28, 2009", "06 July 2008 7:32:47 AM",
            new DateTime(2009, 3, 10), "17:32:47.003" };

    foreach (object value in values)
    {
        try
        {
			//C# Extension Method: Object - ToNullableDateTimeOffSet
            DateTimeOffset? convertedDate = value.ToNullableDateTimeOffSet();
            Console.WriteLine("'{0}' converts to {1}.", value == null ? "null" : value, 
							  convertedDate == null ? "null" : convertedDate.ToString());
        }
        catch (FormatException)
        {
            Console.WriteLine("'{0}' is not in the proper format.", value);
        }
        catch (InvalidCastException)
        {
            Console.WriteLine("Conversion of the {0} '{1}' is not supported",
                              value.GetType().Name, value);
        }
    }
}

View Source
using System;

public static partial class Extensions
{
    /// <summary>
    ///     An object extension method that converts the @this to a nullable date time off set.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>@this as a DateTimeOffset?</returns>
    public static DateTimeOffset? ToNullableDateTimeOffSet(this object @this)
    {
        if (@this == null || @this == DBNull.Value)
        {
            return null;
        }

        return new DateTimeOffset(Convert.ToDateTime(@this), TimeSpan.Zero);
    }
}