Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParseExact method for string comparison

Tags:

c#

linq

Hey how can you do a string comparison match for a given date, DateTime.TryParseExact seems like the sensible option but I am not sure how to construct the arguement in the below method:

public List<Dates> DateEqualToThisDate(string dateentered)
{
    List<Dates> date = dates.Where(
        n => string.Equals(n.DateAdded, 
                           dateentered,
                           StringComparison.CurrentCultureIgnoreCase)).ToList();
        return hiredate;
 }
like image 807
G Gr Avatar asked Jul 26 '12 00:07

G Gr


1 Answers

If you know the format of the date/time exactly (i.e. it never changes, and does not depend on the culture or locale of the user), then you can use DateTime.TryParseExact.

For example:

DateTime result;
if (DateTime.TryParseExact(
    str,                            // The string you want to parse
    "dd-MM-yyyy",                   // The format of the string you want to parse.
    CultureInfo.InvariantCulture,   // The culture that was used
                                    // to create the date/time notation
    DateTimeStyles.None,            // Extra flags that control what assumptions
                                    // the parser can make, and where whitespace
                                    // may occur that is ignored.
    out result))                    // Where the parsed result is stored.
{
    // Only when the method returns true did the parsing succeed.
    // Therefore it is in an if-statement and at this point
    // 'result' contains a valid DateTime.
}

The format string can be a fully specified custom date/time format (such as dd-MM-yyyy), or a general format specifier (such as g). For the latter, the culture matters as to how the date is formatted. For example, in the Netherlands dates are written as 26-07-2012 (dd-MM-yyyy) whereas in the US dates are written as 7/26/2012 (M/d/yyyy).

However, this all only works when your string str contains only the date you want to parse. If you have a bigger string with all sorts of unwanted characters around the date, then you'll have to find the date in there first. This can be done using a regular expression, which is a whole other topic in itself. Some general information about regular expressions (regex) in C# can be found here. A regular expression reference is here. For example, a date similar to d/M/yyyy can be found using the regex \d{1,2}\/\d{1,2}\/\d{4}.

like image 81
Daniel A.A. Pelsmaeker Avatar answered Sep 19 '22 21:09

Daniel A.A. Pelsmaeker