-3

I have a string and I have to convert it into DateTime type.

'11 Jun 2015 (12:10)'

I have to parse it into DateTime. I have used DateTime.Parse("MyDateString") but it is throwing an exception.

String was not recognized as a valid DateTime.

I have to split the string than convert it to DateTime format or there is an easy way?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Farrukh Ahmed
  • 473
  • 4
  • 11
  • 26
  • From the link ckryczek cited above: "DateTime.Parse() will try figure out the format of the given date, and it usually does a good job. If you can guarantee dates will always be in a given format then you can use ParseExact()" – paulsm4 Jun 17 '15 at 08:00

1 Answers1

5

DateTime.Parse uses standard date and time format of your CurrentCulture. Since your string has ( and ), you need to use custom date and time parsing with TryParseExact method (or ParseExact) with an english-based culture (eg: InvariantCulture) like;

string s = "11 Jun 2015 (12:10)";
DateTime dt;
if(DateTime.TryParseExact(s, "dd MMM yyyy '('HH:mm')'", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    // 11.06.2015 12:10:00
}

If your string has ' in the begining and at the end, you can escape them with "\\'dd MMM yyyy '('HH:mm')'\\'" format like;

string s = "'11 Jun 2015 (12:10)'";
DateTime dt;
if(DateTime.TryParseExact(s, "\\'dd MMM yyyy '('HH:mm')'\\'", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    // 11.06.2015 12:10:00
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364