无法在c#中将字符串转换为日期

时间:2014-06-30 08:13:08

标签: c# asp.net-mvc datetime

我有约会时间:

string validDate = formCollection["ValidDate"];

ValidDate值为:

06/24/2014

如果我想将validDate转换为ir.ValidDate,我会收到例外情况。

InterestRate ir = new InterestRate();

ir.ValidDate = Convert.ToDateTime(validDate);

例外:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: String was not recognized as a valid DateTime.

我试过以下。但仍然有例外:

DateTime resultDate = DateTime.ParseExact(validDate , "dd/MM/yyyy", CultureInfo.InvariantCulture);

我到底错过了什么?

3 个答案:

答案 0 :(得分:5)

您的日期格式为MM/dd/yyyy(2014年6月24日),但您尝试将其解析为dd/MM/yyyy

答案 1 :(得分:2)

试试这个: 并将日期dd/MM/yyyy的格式更改为MM/dd/yyyy

DateTime.TryParseExact(validDate, "MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture);

答案 2 :(得分:1)

试试这个

   public class Employee
    {

        public DateTime DateOfJoining { get; set; }

    }

    DateOfJoining = DateTime.Parse("05/02/2014"),