I'm trying to get a date from my database and I've tried different things, but nothing seems to work.
This is my date in the database 2024-04-18 19:47:36.337
, it's defined as datetime
in Microsoft SQL Server; I'm using Entity Framework and C# and the variable is
public DateTime InitH { get; set; }
My query is more complex than this, but I found the problem is the date. So I try to get an optimal solution to search dates
public void obtenerFechaHarcodeada()
{
DateTime fecha = new DateTime(2024, 4, 18, 19, 47, 36);
var registro = _dbContext.AssignmentRecords
.FirstOrDefault(r=> r.InitH == fecha);
}
Any ideas?
I'm trying to save the same date and the same variable to search on the database, but it never works
Rather than an exact date/time value, I suggest that you search for a date/time range that covers the entire second.
DateTime fechaFrom = new DateTime(2024, 4, 18, 19, 47, 36);
DateTime fechaTo = fechaFrom.AddSeconds(1);
var registro = _dbContext.AssignmentRecords
.FirstOrDefault(r=> r.InitH >= fechaFrom && r.InitH < fechaTo);
It is worth noting that the SQL Server DATETIME
type stores times with a precision of 1/300 of a second, so the displayed value 2024-04-18 19:47:36.337
is actually closer to 2024-04-18 19:47:36.33666...
. Like floating point values, it is best to avoid equality comparisons.