On my page I have a form for filtering a list of machines. The form posts with GET method. Two of the fields in that form are text fields for entering a date.
Based on the inputs in the form, I'm filtering the list. My problem is, that the date filtering doesn't work as expected.
The dates are entered in the format dd/MM/yyyy. The system CultureInfo is "da-DK". Dates are stored i MSSQL as yyyy-MM-dd.
I have this filter model:
public class MachineFilter
{
[DisplayName("Search")]
public string Search { get; set; }
[DisplayName("Installation date, from")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? InstallationDateFrom { get; set; }
[DisplayName("Installation date, to")]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime? InstallationDateTo { get; set; }
}
And the filtering (simplified):
[BindProperty(SupportsGet = true)]
public MachineFilter MachineFilter { get; set; }
----
Machines = await _dbContext.Machines.ToListAsync();
if (MachineFilter.InstallationDateFrom != null)
{
Machines = Machines.Where(x => x.InstallationDate != null && x.InstallationDate >= MachineFilter.InstallationDateFrom).ToList();
}
In this example two things can happen: 1) the filtering isn't applied - or 2) wrong results returns to the list.
From this SO question I also tried converting the input to string and back to DateTime with DateTime.ParseExact:
string dateFrom = MachineFilter.InstallationDateFrom?.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
DateTime dFrom = DateTime.ParseExact(dateFrom, "yyyyMMdd", CultureInfo.InvariantCulture);
Machines = Machines.Where(x => x.InstallationDate != null && x.InstallationDate >= dFrom).ToList();
But no matter what I do, I end up with a wrong DateTime format, so entering 01/12/2019 (dd/MM/yyyy) becomes 01/12/2019 (MM/dd/yyyy).
Right now the culture is only "da-DK", so I could do some splitting of the posted input and add a new DateTime(yyyy, MM, dd) of the array, but soon the system will scale to other countries and then dates will be entered as MM/dd/yyyy, so I'd like a more "build-in" approach if possible.
Thanks.