DateTime.TryParseExact Method for String Comparison

Hey, how you can compare strings for a given date DateTime.TryParseExactseems like a reasonable option, but I'm not sure how to build an argument in the following method:

public List<Dates> DateEqualToThisDate(string dateentered)
{
    List<Dates> date = dates.Where(
        n => string.Equals(n.DateAdded, 
                           dateentered,
                           StringComparison.CurrentCultureIgnoreCase)).ToList();
        return hiredate;
 }
+5
source share
2 answers

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

For instance:

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.
}

(, dd-MM-yyyy) (, g). , . , 26-07-2012 (dd-MM-yyyy), 7/26/2012 (M/d/yyyy).

, str , . , . , . (regex) # . . , , d/M/yyyy, \d{1,2}\/\d{1,2}\/\d{4}.

+13

- string DateTime. , DateAdded DateTime.

, LINQPad

public class Dates
{
    public string DateAdded { get; set; }
}

List<Dates> dates = new List<Dates> {new Dates {DateAdded = "7/24/2012"}, new Dates {DateAdded = "7/25/2012"}};

void Main()
{
    DateEqualToThisDate("7/25/2012").Dump();
}

public List<Dates> DateEqualToThisDate(string anything)
{
    var dateToCompare = DateTime.Parse(anything);

    List<Dates> hireDates = dates.Where(n => DateTime.Parse(n.DateAdded) == dateToCompare).ToList();

    return hireDates;
}
0

All Articles