我正在构建日历,我想检查用户输入是否是有效日期。我到目前为止,现在我不知道如何重复消息“无效日期”,直到它是有效的。
我的代码:
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};
Console.Write("\nSet your date: ");
string readAddMeeting = Console.ReadLine();
DateTime scheduleDate;
bool validDate = DateTime.TryParseExact(
readAddMeeting,
dateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out scheduleDate);
if (validDate)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Valid date");
Console.ForegroundColor = ConsoleColor.White;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid date: \"{0}\"", readAddMeeting);
Console.ForegroundColor = ConsoleColor.White;
}
答案 0 :(得分:1)
使用do/while
循环:
do
{
... your code here
}while(!validDate);
答案 1 :(得分:1)
尝试类似:
Mat
答案 2 :(得分:0)
使用do-While循环:
do{
var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};
Console.Write("\nSet your date: ");
string readAddMeeting = Console.ReadLine();
DateTime scheduleDate;
bool validDate = DateTime.TryParseExact(
readAddMeeting,
dateFormats,
DateTimeFormatInfo.InvariantInfo,
DateTimeStyles.None,
out scheduleDate);
if (validDate)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Valid date");
Console.ForegroundColor = ConsoleColor.White;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Invalid date: \"{0}\"", readAddMeeting);
Console.ForegroundColor = ConsoleColor.White;
}
}while(!validDate)