Rahul Singh
Rahul Singh

Reputation: 30

Filter a list of dates (as string) older than x days

Below is the code which is getting the date and filling it into list ,how can i get the days list which is more then 5 days old from today's date.

List<DateTime> fileDate = new List<DateTime>();
for (int i = 0; i <= countofdifffile; i++)
{                        
    fileDate.Add(DateTime.ParseExact(fileListfordiff[i].Substring(22, 8), 
                                     "yyyyMMdd", CultureInfo.InvariantCulture));
}

Upvotes: 0

Views: 686

Answers (2)

TheGeneral
TheGeneral

Reputation: 81493

linq solution

Older than 5 days

List<DateTime> fileDates = fileListfordiff 
        // parse your list into usable Dates
        .Select(x => DateTime.ParseExact(x.Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture))
        // filter the list by age older than 5 days ago
        .Where(x => x < DateTime.Now.AddDays(-5))
        // return a List<DateTime> i.e file dates
        .ToList();

Younger than 5 days ago

List<DateTime> fileDates = fileListfordiff 
        // parse your list into usable Dates
        .Select(x => DateTime.ParseExact(x.Substring(22, 8), "yyyyMMdd", CultureInfo.InvariantCulture))
        // filter the list by age < 5 days ago
        .Where(x => x > DateTime.Now.AddDays(-5))
        // return a List<DateTime> i.e file dates
        .ToList();

Upvotes: 0

Nikhil Agrawal
Nikhil Agrawal

Reputation: 48558

You simply need to do

List<DateTime> fileDate = new List<DateTime>();
for (int i = 0; i <= countofdifffile; i++)
{                        
    var dt = DateTime.ParseExact(fileListfordiff[i].Substring(22, 8), 
                                 "yyyyMMdd", CultureInfo.InvariantCulture)
    fileDate.Add(dt);
    fileDate.Add(dt.AddDays(-5)); // Adds 5 days less date.
}

Upvotes: 1

Related Questions