【问题标题】:C# How to read and print date in switch [closed]C#如何在开关中读取和打印日期[关闭]
【发布时间】:2016-06-22 22:20:02
【问题描述】:

我想把这个日期放在一个 while 循环内的 switch 语句中。不知道在哪里声明变量以使其工作。我还想让字符串日期处理错误的输入。这在字符串上是如何工作的?

string date = Console.ReadLine();
DateTime dt = Convert.ToDateTime(date);            
Console.WriteLine("{0}/{1}/{2}", dt.Year, dt.Month, dt.Day);

这是我的代码

while(true) {
   Console.WriteLine("[1] Enter date (dd/mm/yyyy)");
   Console.WriteLine("[2] Print date");
   Int32.TryParse (Console.ReadLine(), out answer);

   switch (answer) {
   case 1:
   break;
   }

   case 2:
   break;
   }    
}

【问题讨论】:

  • 要处理无效日期,最好使用DateTime.TryParse
  • 有时最好买一本书读一读,而不是问没有重点的问题。学习编程很难!

标签: c# date while-loop switch-statement


【解决方案1】:

听起来你想在循环外有一个DateTime 变量,你可以使用DateTime.TryParse 来确定他们输入的日期是否有效。如果您只想允许输入一种日期格式,也可以使用DateTime.TryParseExact。您也可以允许他们结束循环。

DateTime dt = new DateTime();
bool keepGoing = true;
while (keepGoing)
{
    Console.WriteLine("[1] Enter date (dd/mm/yyyy)");
    Console.WriteLine("[2] Print date");
    Console.WriteLine("[3] Stop");
    int answer;
    int.TryParse(Console.ReadLine(), out answer);

    switch (answer)
    {
        case 1:
            if(!DateTime.TryParse(Console.ReadLine(), out dt))
            {
                Console.WriteLine("Invalid Date");
            }
            break;
        case 2:
            Console.WriteLine("{0}/{1}/{2}", dt.Year, dt.Month, dt.Day);
            break;
        case 3:
            keepGoing = false;
            break;
        default:
            Console.WriteLine("Incorrect Entry");
            break;
    }
}

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多