简体   繁体   中英

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

I am Compairing the date formats and it works fine for dd-MM-yyyy input but throws exception for 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 that DateTime.ParseExact expects date only in "dd-MM-yyyy" format. Parsing any other format of date string will throw FormatException as it is specified in Documentation :

FormatException is thrown when s does not contain a date and time that corresponds to the pattern specified in format .

If you want to support several formats, you should provide all of them. That is possible to do with DateTime.ParseExact overload which accepts array of formats:

 var formats = new [] {"dd-MM-yyyy", "dd/MM/yyyy" };
 var d = DateTime.ParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM