Object - IsValidDateTime
An object extension method that query if '@this' is valid System.DateTime.
public static void Main() { string format = "{0, -30} {1, -15}"; object [] values = { "-128" , "-89","ABC", "true", "12/31/2018", "a", ".", "0", "10.2m", "4/2/2007 7:23:57 PM -07:00"}; Console.WriteLine(format, "Object", "Is Valid DateTime"); Console.WriteLine(format, "------", "-----------------"); foreach(var val in values) { // C# Extension Method: Object - IsValidDateTime Console.WriteLine(format, val, val.IsValidDateTime()); } }
View Source
using System; public static partial class Extensions { /// <summary> /// An object extension method that query if '@this' is valid System.DateTime. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>true if valid System.DateTime, false if not.</returns> public static bool IsValidDateTime(this object @this) { if (@this == null) { return true; } DateTime result; return DateTime.TryParse(@this.ToString(), out result); } }