[英]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
. 我正在编译日期格式,它对于
dd-MM-yyyy
输入工作正常,但是对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. 您已指定
DateTime.ParseExact
仅以"dd-MM-yyyy"
格式期望日期。 Parsing any other format of date string will throw FormatException as it is specified in Documentation : 解析日期字符串的任何其他格式都会抛出FormatException,如文档中所指定:
FormatException is thrown when s does not contain a date and time that corresponds to the pattern specified in format .
如果s不包含与format中指定的模式相对应的日期和时间,则引发FormatException。
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:
这可能与DateTime.ParseExact重载有关,该重载接受格式数组:
var formats = new [] {"dd-MM-yyyy", "dd/MM/yyyy" };
var d = DateTime.ParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.