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

Dani AI

Generated

A practical, reliable approach for scraping dates from arbitrary text is a two-step pipeline: 1) extract short candidate substrings that look like dates (ISO fragments, month-name phrases, numeric groups) with a lightweight regex, and 2) try parsing each candidate with the built-in parsers and a small list of expected formats. This avoids relying on the whole input matching a single date format and gives fast fallbacks when formats vary. pointed to the regex idea; this expands that into a robust workflow and avoids false negatives. (learn.microsoft.com)

Example tactic (C#): run a single, permissive regex to grab tokens, then attempt a parse-per-token using culture-aware parsing and one or two TryParseExact patterns as fallbacks. The parser methods accept an IFormatProvider and DateTimeStyles so you can force invariant parsing or control how two-digit years and time zones are handled. Use TryParseExact when you know a small set of likely formats. (learn.microsoft.com)

Keep time zones in mind: if input can include offsets or zone names, parse into DateTimeOffset (or convert after parsing) instead of plain DateTime so the moment is unambiguous across machines. Treat DateTime as local/unspecified unless you convert it deliberately. Also prefer ISO-8601 when you can change the source; it is the least ambiguous format. (learn.microsoft.com)

Cautions and tips: build a few focused regex patterns (ISO timestamps, month-name forms, numeric dates) rather than one huge pattern, and pass a timeout or use compiled/anchored patterns to avoid catastrophic backtracking. For heavy-duty or timezone-correct parsing consider a library like Noda Time and its parsing patterns when correctness matters. Finally, log which formats succeed so you can iteratively refine the formats list for your corpus. (learn.microsoft.com)

Code sketch (not in-post duplicate of earlier examples):

// find short date-like tokens, try DateTimeOffset then TryParseExact fallbacks
static bool TryFindDate(string text, out DateTimeOffset found)
{
    found = default;
    var rx = new Regex(@"\b(?:\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}|\w{3,9}\s\d{1,2},\s?\d{4}|\d{1,2}[-/]\d{1,2}[-/]\d{2,4})\b",
                       RegexOptions.Compiled | RegexOptions.IgnoreCase);
    foreach (Match m in rx.Matches(text))
    {
        var s = m.Value;
        if (DateTimeOffset.TryParse(s, CultureInfo.InvariantCulture, DateTimeStyles.None, out found))
            return true;
        // fallback: TryParseExact with a small formats[] using InvariantCulture
    }
    return false;
}

This pattern is efficient for mixed web content and easy to extend as you see new date shapes in the wild.

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.