字符串不是c#中的有效日期时间

时间:2014-10-13 10:53:16

标签: c# string datetime

当我尝试将字符串“25-12-2014 15:35”转换为DateTime时,我得到一个例外,即该字符串不是有效的DateTime。如何避免此异常?

String Mydate= col.Get("StartDate");
DateTime startDate = DateTime.ParseExact(MyString, "dd-MM-yyyy", null);

2 个答案:

答案 0 :(得分:3)

来自documentation;

  

将指定的日期和时间字符串表示形式转换为   它的DateTime等效使用指定的格式和   特定文化的格式信息。 字符串的格式   表示必须与指定的格式完全匹配。

在你的情况下,他们不是。您没有使用任何格式的小时和分钟部分。请改用dd-MM-yyyy HH:mm格式。

string s = "25-12-2014 15:35";
DateTime dt;
if(DateTime.TryParseExact(s, "dd-MM-yyyy HH:mm", null,
                          DateTimeStyles.None, out dt))
{
    Console.WriteLine(dt);
}

由于您使用null作为IFormatProvider,因此默认使用CurrentCulture。如果您的CurrentCulture TimeSeparator property不是:,如果您的日期字符串和格式字符串格式相同,那么您的解析操作将失败甚至

在这种情况下,您可以使用CultureInfo.Clone method克隆当前的文化,并将其TimeSeparator属性设置为:,或者您可以使用InvariantCulture已经:作为时间分隔符。

答案 1 :(得分:1)

您可以尝试完全解析它:

DateTime d = DateTime.ParseExact("25-12-2014 15:35", "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture);

或使用正确的文化(例如荷兰语):

DateTime d = DateTime.Parse("25-12-2014 15:35", new CultureInfo("nl-NL"));