C# 格式化日期时未获得预期的输出
我希望我的程序验证日期格式是否为C# 格式化日期时未获得预期的输出,c#,datetime,datetime-parsing,C#,Datetime,Datetime Parsing,我希望我的程序验证日期格式是否为mm/dd/yyyy。我不想使用任何抛接球挡块 class FunWithScheduling { public void AddView() { ... ... Console.WriteLine("Enter the Date Scheduled For the Meeting:"); string Date = Console.ReadLine(); DateT
mm/dd/yyyy
。我不想使用任何抛接球挡块
class FunWithScheduling
{
public void AddView()
{
...
...
Console.WriteLine("Enter the Date Scheduled For the Meeting:");
string Date = Console.ReadLine();
DateTime date = DateTime.Parse(Date);
string formatted = date.ToString("MM-dd-yyyy");
if (Date != formatted)
Console.WriteLine("Invalid Choice");
...
...
}
static void Main()
{
FunWithScheduling a = new FunWithScheduling();
a.AddView();
}
}
尝试:
尝试:
签出
DateTime.TryParseExact
签出DateTime.TryParseExact
您需要更改此行
DateTime date = DateTime.Parse(Date);
到
你需要换一行
DateTime date = DateTime.Parse(Date);
到
DateTime date;
if(!DateTime.TryParseExact(Date,"MM-dd-yyyy",new CultureInfo("en-US"),
DateTimeStyles.None,
out date))
{
Console.WriteLine("Invalid Choice");
}