【问题标题】:Converting an inputted string into a date将输入的字符串转换为日期
【发布时间】:2014-03-19 11:50:38
【问题描述】:

我一直在尝试将日期转换为 wrok,以便从字符串转换为日期,我查看了 msdn 和其他一些堆栈 o 问题,但多种方法都没有奏效。我正在制作一个控制台应用程序,它需要一个有效日期来检查其他日期。以下是我目前的尝试。

string StartDate, EndDate;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
StartDate = DateTime.Parse(StartDate);

我目前设置变量StartDate,然后根据用户输入的内容设置一个值,然后它应该使用Parse将其更改为日期

【问题讨论】:

标签: c# parsing date readline


【解决方案1】:

您试图将DateTime 值分配给字符串StartDate,这是错误的。所以修改如下:

string StartDate, EndDate;
DateTime date;       
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
date = DateTime.Parse(StartDate);

【讨论】:

    【解决方案2】:

    string 不是DateTimeDateTime 不是String。因此,您可能能够将字符串解析为日期,但不能将字符串变量用于 DateTime,反之亦然。你需要两个变量:

    string startDateInput = Console.ReadLine();
    DateTime startDate = DateTime.Parse( startDateInput );
    

    如果输入字符串不是有效日期,这可能会失败,您应该使用TryParse

    DateTime startDate;
    bool validDate = DateTime.TryParse(startDateInput, out startDate);
    if(validDate)
        Console.Write("Valid date: " + startDate.ToLongDateString());
    

    【讨论】:

    • jsut 所以我理解你的方法,它很好,请为我解释这部分DateTime.TryParse(startDateInput, out startDate); INB4 我是 C# 新手
    • DateTime.TryParse 类似于 DateTime.Parse。如果String 是有效/受支持的格式,两者都可以将其解析为DateTime。但是Parse 会在格式错误时抛出异常,而TryParse 返回一个bool,表示它是否可以被解析。 out 参数在成功时返回已解析的 DateTime。有关详细信息,请参阅 MSDN:msdn.microsoft.com/en-us/library/ee332485.aspx
    【解决方案3】:

    尝试使用Convert.ToDateTime();

    例子:

    string date = "01/08/2008";
    DateTime dt = Convert.ToDateTime(date);
    

    【讨论】:

    • Convert.ToDateTime(string) 方法明确使用DateTime.Parse(string)。由于DateTime.Parse 在OP 的代码中不起作用,这意味着Convert.ToDateTime 方法也不起作用。
    【解决方案4】:

    使用DateTime.TryParse()

    将日期和时间的指定字符串表示形式转换为其 DateTime 等效并返回一个值,该值指示是否 转换成功。

    DateTime date;
    
    if (!DateTime.TryParse("DateString", out date))
       {
          MessageBox.Show("Invalid string!");
       }
    

    【讨论】:

      【解决方案5】:

      您需要指定日期格式。

      试试这个:示例格式MM-dd-yyyy

      Console.WriteLine("Input Start date Format -> MM-dd-yyyy");
      string StartDate = Console.ReadLine();
      DateTime YourDate = DateTime.ParseExact(StartDate,"MM-dd-yyyy", 
                          System.Globalization.CultureInfo.InvariantCulture);
      

      【讨论】:

      • 这没用,但这个方法试图达到什么目的,因为我是新手,如果我理解它会有所帮助,我以前从未见过CultureInfo.InvariantCulture
      • 当您预先知道用户输入的格式作为输入时,您可以使用此方法。例如,如果用户输入日期为MM-dd-yyyy,那么它使用格式MM-dd-yyyy 解析与日期相同的日期,顺便说一句did not work 意味着什么问题? CultureInfo.InvariantCulture 用于解析culture-independent中的日期
      • 我明白你的意思,我认为这是一个语法错误,所以我现在就来复习一下 :)
      • 您需要导入using System.Globalization; 命名空间或查看我编辑的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 1970-01-01
      • 2011-11-28
      • 1970-01-01
      • 2016-05-03
      相关资源
      最近更新 更多