c# - Check if a string is a valid date using DateTime.TryParse -
i using datetime.tryparse()
function check if particular string valid datetime not depending on cultures.
surprise , function returns true
strings "1-1", "1/1" .etc.
how can solve problem?
update:
does mean, if want check if particular string valid datetime, need huge array of formats?? there different combinations , believe.
even there lots of date separator ( '.' , '/' , '-', etc..) depending on culture, difficult me define array of format check against .
basically, want check if particular string contains @ least day(1 through 31 or 01 through 31),month(1 through 12 or 01 through 12) , year(yyyy or yy) in order, date separator , solution?
so, if value includes parts of time, should return true too. not able define array of format.
if want dates conform particular format or formats use datetime.tryparseexact
otherwise default behaviour of datetime.tryparse
this method tries ignore unrecognized data, if possible, , fills in missing month, day, , year information current date. if s contains date , no time, method assumes time 12:00 midnight. if s includes date component two-digit year, converted year in current culture's current calendar based on value of calendar.twodigityearmax property. leading, inner, or trailing white space character in s ignored.
if want confirm against multiple formats @ datetime.tryparseexact method (string, string[], iformatprovider, datetimestyles, datetime) overload. example same link:
string[] formats= {"m/d/yyyy h:mm:ss tt", "m/d/yyyy h:mm tt", "mm/dd/yyyy hh:mm:ss", "m/d/yyyy h:mm:ss", "m/d/yyyy hh:mm tt", "m/d/yyyy hh tt", "m/d/yyyy h:mm", "m/d/yyyy h:mm", "mm/dd/yyyy hh:mm", "m/dd/yyyy hh:mm"}; string[] datestrings = {"5/1/2009 6:32 pm", "05/01/2009 6:32:05 pm", "5/1/2009 6:32:00", "05/01/2009 06:32", "05/01/2009 06:32:00 pm", "05/01/2009 06:32:00"}; datetime datevalue; foreach (string datestring in datestrings) { if (datetime.tryparseexact(datestring, formats, new cultureinfo("en-us"), datetimestyles.none, out datevalue)) console.writeline("converted '{0}' {1}.", datestring, datevalue); else console.writeline("unable convert '{0}' date.", datestring); } // example displays following output: // converted '5/1/2009 6:32 pm' 5/1/2009 6:32:00 pm. // converted '05/01/2009 6:32:05 pm' 5/1/2009 6:32:05 pm. // converted '5/1/2009 6:32:00' 5/1/2009 6:32:00 am. // converted '05/01/2009 06:32' 5/1/2009 6:32:00 am. // converted '05/01/2009 06:32:00 pm' 5/1/2009 6:32:00 pm. // converted '05/01/2009 06:32:00' 5/1/2009 6:32:00 am.
Comments
Post a Comment