C# - System.FormatException: Invalid format string at System.DateTime -


i compairing date formats , works fine dd-mm-yyyy input throws exception dd/mm/yyyy.

my code:

string s = console.readline(); datetime d = datetime.parseexact(s, "dd-mm-yyyy", cultureinfo.invariantculture); string h = d.tostring("dd-mm-yyyy"); if (h.equals(s)) {     console.writeline("valid"); } else {     console.writeline("invalid"); } 

you have specified datetime.parseexact expects date in "dd-mm-yyyy" format. parsing other format of date string throw formatexception specified in documentation:

formatexception thrown when s not contain date , time corresponds pattern specified in format.

if want support several formats, should provide of them. possible datetime.parseexact overload accepts array of formats:

 var formats = new [] {"dd-mm-yyyy", "dd/mm/yyyy" };  var d = datetime.parseexact(s, formats, cultureinfo.invariantculture, datetimestyles.none) 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -