Hi,
I have a string that might include a date as substring. For example the string may be "Oct 23, 2008 16:41:58 GMT Unassigned". I would like to check if a substring of the given string can be converted to a date. I tried using:

public static bool IsDate(String str)
        {
                DateTime dt;
                return DateTime.TryParse(str, out dt);
        }

But it only finds exact date format. Is there a library that does this?
Thanks

Recommended Answers

All 3 Replies

If you know that the datetime is always in the same format as in your example then it will always be of a fixed length.
Also, if the date is always at the start of the string then you can use String.SubString to extract the date part to test.
E.g. return DateTime.TryParse(str.Substring(0, 25), out dt); If the date might not be at the start of the string then you will need to test for a match using a Regex. E.g.

// regex string to match the example date format in your post.
// Note: if the date format changes this will need to be adapted.
string My_Date_Regex = @"\b\w{3}\s\d{2},\s\d{4}\s(\d{2}:){2}\d{2}\s\w{3}";
// Regex is found in System.Text.RegularExpressions namespace
Regex rx = new Regex(My_Date_Regex);
// parse string for My_Data_Regex format, true if found.
return rx.IsMatch(str)

If the date/time format varies then you might need to use several Regex tests.
Or if possible change the code that generates the string to ensure that it is always in the same format.
(I would strongly recommend either RFC1123 or ISO8601 format as these do not change with UI culture.)

Thank you for your detailed answer,
As I am trying to parse general web pages, I do not know the format of the date, nor that it is at the beginning of the text. This means that I do not know the length of the date field.

From your answer I get that the best way to recognize the relevant strings is to use regular expressions. If I want to support several formats, I have to use several expressions. Did I understand correctly?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.