ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsDate

Determines if specified string is DateTime. Its an improvement on Phil Campbell's version

Source

public static bool IsDate(this string input)
{
  DateTime dt;
  return (DateTime.TryParse(input, out dt));
}

Example

Assert.IsTrue("23 March 2003".IsDate());
Assert.IsTrue("1 August -2003".IsDate());
Assert.IsTrue("2013-1-25".IsDate());
Assert.IsTrue("May 30, 2009".IsDate());

Assert.IsFalse("23 JulyAugust 2003".IsDate());
Assert.IsFalse("38 August 2003".IsDate());
Assert.IsFalse("2013-13-25".IsDate());
Assert.IsFalse("2013-10-92".IsDate());
Assert.IsFalse("-2013-1-3".IsDate());
Assert.IsFalse("May 32, 2009".IsDate());

Assert.IsFalse("One flew over the Cookoo's nest".IsDate());
Assert.IsFalse("".IsDate());
Assert.IsFalse(string.Empty.IsDate());
Assert.IsFalse(((string)null).IsDate());

Author: CodeMonkey

Submitted on: 9 mrt. 2016

Language: C#

Type: System.String

Views: 4298