user3868071
user3868071

Reputation: 23

String is not a valid Date time in c#

When I try to convert the string "25-12-2014 15:35" to a DateTime, I get an exception that the string is not a valid DateTime. How do I avoid this exception?

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

Upvotes: 0

Views: 680

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98740

From documentation;

Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

In your case, they are not. You didn't use any format for your hours and minutes part. Use dd-MM-yyyy HH:mm format instead.

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);
}

Since you used null as a IFormatProvider, it uses CurrentCulture by default. And if your CurrentCulture's TimeSeparator property is not :, your parsing operation will fail even if your date string and format string have the same format.

In such a case, you can clone your current culture with CultureInfo.Clone method and set it's TimeSeparator property to : or you can use InvariantCulture which has already : as a time separator.

Upvotes: 3

Patrick Hofman
Patrick Hofman

Reputation: 156928

You could try to parse it exact:

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

Or use the right culture (for example Dutch):

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

Upvotes: 1

Related Questions