-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?

1
  • 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()" Commented Jun 17, 2015 at 8:00

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.