How to validate DateTime format?
Are you looking for something like this?
DateTime expectedDate;
if (!DateTime.TryParse("07/27/2012", out expectedDate))
{
Console.Write("Luke I am not your datetime.... NOOO!!!!!!!!!!!!!!");
}
If your user knows the exact format(s) needed...
string[] formats = { "MM/dd/yyyy", "M/d/yyyy", "M/dd/yyyy", "MM/d/yyyy" };
DateTime expectedDate;
if (!DateTime.TryParseExact("07/27/2012", formats, new CultureInfo("en-US"),
DateTimeStyles.None, out expectedDate))
{
Console.Write("Thank you Mario, but the DateTime is in another format.");
}
Unless I am remembering incorrectly, the only invalid DateTime format strings are one character long. You can assume any 2 or more character DateTime format string is valid.
DateTime.ParseExact("qq", "qq", null) == DateTime.Today
DateTime.ParseExact("myy", "501", null) == "05/01/2001"
Standard (1 character)
Custom (>1 character)
For reference, allowed single character strings as formats:
d,D,f,F,g,G,m,M,o,O,r,R,s,T,u,U,y,Y
Any other character, such as q
, by itself is invalid. All other strings will be successfully parsed as formatting strings.
I assume you want to know if the specified format string is valid...
For this you could round-trip it:
private bool IsValidDateFormat(string dateFormat)
{
try
{
String dts=DateTime.Now.ToString(dateFormat, CultureInfo.InvariantCulture);
DateTime.ParseExact(dts, dateFormat, CultureInfo.InvariantCulture);
return true;
}
catch (Exception)
{
return false;
}
}
I don't know of any way to actually validate the format they enter since sometimes you want to intentionally include characters that translate into anything. One thing you might consider is allowing the user to self validate by showing a preview of what their entered format translates into.