-4

I have a table that has date time stored as follows

2022-02-01 17:47:50.3483971 +00:00
2022-05-11 18:47:50.3483971 +00:00
2022-05-21 14:40:50.3483971 +00:00

I'm trying to write a linq query that will compare get results for the date passed but i only want to pass in the date, for example get the records from 2022/02/01

so I tried

var fdate=  query.filteredDate.LocalDateTime.ToShortDateString(); // this gets the date the user passes in.

the problem comes in the where clause when I try this

filteredResult.Where(x=> fdate >= DateTime.Parse(x.storeddate.LocalDateTime.ToShortDateString()))

then it errors out and says can not be applied to string and datetime

so I tried this

Where(x=> fdate >= x.storeddate.LocalDateTime.ToShortDateString()))

and it says can not be applied to string and string

what am I doing wrong?

Filburt
  • 17,626
  • 12
  • 64
  • 115
deanpillow
  • 121
  • 1
  • 10
  • 2
    Strings aren't dates. – Dai Jun 15 '22 at 07:07
  • 1
    ... and there is no defined `>= operator` for them(strings) – Selvin Jun 15 '22 at 07:07
  • convert `fdate` to `DateTimeOffset` (as it seems to be string) abd then compare it to `x.storeddate.LocalDateTime` – Selvin Jun 15 '22 at 07:08
  • 1
    You can simply use the [DateTime.Date](https://learn.microsoft.com/en-us/dotnet/api/system.datetime.date?view=net-6.0) property if you only want the Date part. No need for mucking around with strings. – Filburt Jun 15 '22 at 07:15

1 Answers1

-1

here I've write an some code to resolve your issue:

List<DateTime> ListDatesToCompare = new List<DateTime>(); //that list simulate your input list
ListDatesToCompare.Add(new DateTime(2022, 02, 01, 17, 47, 50, 348, DateTimeKind.Utc));
ListDatesToCompare.Add(new DateTime(2022, 05, 11, 18, 47, 50, 348, DateTimeKind.Utc));
ListDatesToCompare.Add(new DateTime(2022, 05, 21, 14, 40, 50, 348, DateTimeKind.Utc));

//this is your filter in string format
string fdate = "2022/02/01"; 

//for this example i've forced the culture info to be sure that the date will be correctly parsed (here some documentation: https://stackoverflow.com/questions/13797727/datetime-and-cultureinfo)
DateTime fDateParsed = DateTime.Parse(fdate, new System.Globalization.CultureInfo("en-EN")); 

//here the result query
List<DateTime> ResultOfQuery = ListDatesToCompare.Where((DateTime CurrentDT) => 
    { 
        //you can do this comparison because the variables has the same type.
        return CurrentDT >= fDateParsed;
    }).ToList();

I hope the code and my english is understandable, if you need something else text to me.

Filburt
  • 17,626
  • 12
  • 64
  • 115