C# Extension Method: Object - ToDateTime

CSharp · Console

/Program.cs

// C# Extension Method
// Doc: https://csharp-extension.com/en/method/1002478/object-todatetime

// @nuget: Z.ExtensionMethods

using System;
					
public class Program
{
	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 - ToDateTime
                DateTime convertedDate = value.ToDateTime();
                Console.WriteLine("'{0}' converts to {1}.", value, convertedDate);
            }
            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);
            }
        }
	}
}
;