【问题标题】:Inputing a date from console in C#在 C# 中从控制台输入日期
【发布时间】:2017-02-06 19:17:30
【问题描述】:

我的时间和日期系统适用于今天、明天和设定的日期。现在我想为系统创建某种 Console.Read 以便您可以输入任何日期并接收相应的日期。

    static void date()
    {
        DateTime now = DateTime.Today;
        Console.WriteLine("Today's date is {0}\n", now);

        DateTime currTimeAndDate = DateTime.Now;
        Console.WriteLine("Today's time and date is {0}\n", currTimeAndDate);

        DateTime tomorrow = currTimeAndDate.AddDays(1);
        Console.WriteLine("Tomorrow's date will be {0}\n", tomorrow);

        DateTime then = new DateTime(1995,4,28);
        Console.WriteLine("I was born {0}\n", then.DayOfWeek);
        Console.Write("Press any key to continue.....\n");
        Console.ReadLine();
    }

    static void inputDate()
    {            
        Console.ReadLine();
    }

}

}

【问题讨论】:

  • 究竟是什么问题?如何输入日期时间?如果一切都失败了,输入一个字符串,然后在上面使用Convert.ToDateTime
  • 在静态 void inputDate 中,我想从输入中获取一些东西,例如 'code' static void inputDate() { DateTime year; Console.WriteLine("|-------------------------------------------- ----------------------------------|"); year = Console.WriteLine("请使用 MM/DD/YY 格式输入日期"); Console.ReadLine(year + then.DayOfWeek) }
  • 所以实现该代码,然后告诉我们它是否有效。如果没有,请说明原因以及您收到了哪些错误/异常。

标签: c# datetime


【解决方案1】:

由于这是一个控制台应用程序,我建议使用 TryParse 方法,如下所示。

Console.WriteLine("Enter a date: ");
DateTime userDateTime;
if (DateTime.TryParse(Console.ReadLine(), out userDateTime))
{
     Console.WriteLine("The day of the week is: " + userDateTime.DayOfWeek);
}
else
{
     Console.WriteLine("You have entered an incorrect value.");
}
Console.ReadLine();

【讨论】:

    【解决方案2】:

    这取决于您希望如何让用户输入日期。您可以让他们分别输入月、日和年,如下所示:

    Console.Write("Enter a month: ");
    int month = int.Parse(Console.ReadLine());
    Console.Write("Enter a day: ");
    int day = int.Parse(Console.ReadLine());
    Console.Write("Enter a year: ");
    int year = int.Parse(Console.ReadLine());
    
    DateTime inputtedDate = new DateTime(year, month, day);
    

    如果需要,您可以让他们输入实际日期:

    Console.Write("Enter a date (e.g. 10/22/1987): ");
    DateTime inputtedDate = DateTime.Parse(Console.ReadLine());
    

    请记住,这些只是示例。在实际程序中,您应该检查以确保输入的值是真实的。此外,您可以使用DateTime.ParseExact() 代替DateTime.Parse(),以允许用户以自定义格式输入日期。

    【讨论】:

    • 虽然代码有效,但与我在沮丧并删除它之前的最初想法相似,但它不会打印出与日期相对应的哪一天(即:星期五)。
    猜你喜欢
    • 2019-02-15
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多