Reputation: 5075
I need to compare two date ranges against a records list using LINQ, and for some reason I'm stuck badly. I am receiving date in string format which I am converting to DateTime. I know there is data within the specific date range in database so I should get records back.
public static string FilterStudentListInRelationToStaffByDateRange(
string GivenStaffID,
string SelectFilterOption,
string FromDate,
string ToDate)
{
var dt = DateTime.Parse(FromDate);
// var fff = String.Format("{0:d/M/yyyy hh:mm:ss}", dt);
var dt3 = DateTime.Parse(ToDate);
//var fff3 = String.Format("{0:d/M/yyyy hh:mm:ss}", dt3);
var x = (from b in queryList
where b.RelationshipDateStart >= dt && b.RelationshipDateEnd <= dt3
select b).ToList();
Upvotes: 0
Views: 896
Reputation: 5757
Date/time parsing can be annoying, specially if you handle different formats.
If you know the format, you can try using DateTime.ParseExact
:
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "d/M/yyyy hh:mm:ss";
try
{
var dt = DateTime.ParseExact(FromDate, format, provider);
var dt3 = DateTime.ParseExact(ToDate, format, provider);
var x = (from b in queryList
where b.RelationshipDateStart >= dt && b.RelationshipDateEnd <= dt3
select b).ToList();
}
catch (FormatException)
{
Console.WriteLine("Date is not in the correct format.");
}
Upvotes: 1