Neil Gilbert
Neil Gilbert

Reputation: 145

Check DateTime is valid in Linq Where clause

How do i check in my linq where clause if the date is valid and then query on the valid date ? I've tried this but it throws an error on the invalid dates.

var dates = new List<string>();
    dates.Add("21/11/2016");
    dates.Add("25/10/1975");
    dates.Add("31/2/2016");
    dates.Add("asdad");
    dates.Add("");
            
    var validDates = dates.Where(x => DateTime.Parse(x) < DateTime.Today).ToList();

or this but it returns no results

DateTime isValid;
var validDates = dates.Where(x => DateTime.TryParse(x, out isValid) && DateTime.Parse(x) < DateTime.Today).ToList();

Upvotes: 0

Views: 1250

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186718

Try providing explicit format with a help of TryParseExact:

var validDates = dates
  .Where(s => DateTime.TryParseExact(
                  s, 
                 "d/M/yyyy", 
                  CultureInfo.InvariantCulture, 
                  DateTimeStyles.AssumeLocal, 
                  out var date) && 
              date < DateTime.Today)
  .ToList();

Note, that there's no need to parse twice: you can use the outcome (date) of the TryParse to test with DateTime.Today.

Upvotes: 2

Related Questions