0

I need to search for, and parse, a datetime (formatted based on current culture) in a string.

The best I can come up with at the moment is:

string text = String.Format("Time is {0}; all's well", DateTime.Now);
DateTime date = new DateTime();
for (int start = 0; start < text.Length - 1; start++)
    for (int length = text.Length - start; length > 0; length--)
        if (DateTime.TryParse(text.Substring(start, length), out date))
            return date;

Is there a smarter way to do this?

Murray
  • 1,948
  • 1
  • 12
  • 18
  • 1
    do you know anything more about the string in which you will be looking for? Or should it be arbitrary string? – Jarek Jun 06 '13 at 10:26
  • Without knowing more about the structure of the string and how the datetime is presented in it, there is nothing for us to work on. Do you mean it is _always_ as the example ("Time is...")? – Oded Jun 06 '13 at 10:30

2 Answers2

0

A better approach is to split the string using common delimiters (such as space and ; in your example), then try to parse each part (and/or concatenate every two parts together).

If you know the date to always be in a specific position within the split, you can eliminate the looping and get the date string directly.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
0

Sounds hard. Probably a job for regular expressions. Given that you said

formatted based on current culture

you'll need a regular expression per culture, and pick the right one based on the culture set.

Alternatively, if you know what the surrounding text will be, i.e. the ("Time is {0}; all's well") part, then you could remove that from the string first, and then try a

DateTime.TryParse(dateOnlyString, currentCulture, ...)
harriyott
  • 10,505
  • 10
  • 64
  • 103