¿Cómo comparar solo Fecha sin hora en tipos de fecha y hora en Linq con SQL con Entity Framework?


Hay una manera de comparar 2 variables DateTime en Linq2Sql pero de ignorar la parte de Tiempo.

La aplicación almacena elementos en la base de datos y agrega una fecha de publicación. Quiero mantener la hora exacta, pero todavía ser capaz de tirar de la fecha en sí.

Quiero comparar 12/3/89 12:43:34 y 12/3/89 11:22:12 y tiene caso omiso de la hora real del día para que ambos son considerados de la misma.

Supongo que puedo establecer todas las horas del día a 00:00:00 antes de comparar, pero en realidad lo hago quiero saber la hora del día que también quiero ser capaz de comparar por fecha solamente.

Encontré un código que tiene el mismo problema y comparan el año, el mes y el día por separado. ¿Hay una mejor manera de hacer esto?

Author: Korayem, 2009-03-25

10 answers

Intente usar la propiedad Date en el objeto DateTime...

if(dtOne.Date == dtTwo.Date)
    ....
 421
Author: Quintin Robinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-25 19:19:21

Para una comparación verdadera, puede usar:

dateTime1.Date.CompareTo(dateTime2.Date);
 51
Author: Reed Copsey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-25 19:20:51

Así es como hago esto para trabajar con LINQ.

DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
                EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));

Si solo usa dtOne.Date == dtTwo.Date no funcionará con LINQ (Error: El miembro de tipo especificado 'Date' no es compatible con las entidades LINQ to)

 26
Author: Alejandro del Río,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-17 09:30:37
DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
    MessageBox.Show("Valid Date");
}
else
{
    MessageBox.Show("Invalid Date... Please Give Correct Date....");
}
 12
Author: Devarajan.T,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-03 15:56:51

Debe usar EntityFunctions.TruncateTime con EF DbFunctions.TruncateTime en EF > 6.0 alrededor de cualquier propiedad DateTime que desee usar dentro de su Linq.

Ejemplo

var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate) 
                                       > DbFunctions.TruncateTime(DateTime.UtcNow));
 12
Author: Korayem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-17 12:27:24
DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}

Puede usar esto si está utilizando campos de datos nullables.

 5
Author: Code Geek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-10 13:53:12
DateTime dt1=DateTime.ParseExact(date1,"dd-MM-yyyy",null);
DateTime dt2=DateTime.ParseExact(date2,"dd-MM-yyyy",null);

int cmp=dt1.CompareTo(dt2);

   if(cmp>0) {
       // date1 is greater means date1 is comes after date2
   } else if(cmp<0) {
       // date2 is greater means date1 is comes after date1
   } else {
       // date1 is same as date2
   }
 4
Author: Mohan Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-30 12:27:22
DateTime econvertedDate = Convert.ToDateTime(end_date);
DateTime sconvertedDate = Convert.ToDateTime(start_date);

TimeSpan age = econvertedDate.Subtract(sconvertedDate);
Int32 diff = Convert.ToInt32(age.TotalDays);

El valor diff representa el número de días para la edad. Si el valor es negativo, la fecha de inicio cae después de la fecha de finalización. Este es un buen cheque.

 2
Author: dgsjr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-23 14:52:06

En su cláusula join o where, use la propiedad Date de la columna. Entre bastidores, esto ejecuta una operación CONVERT(DATE, <expression>). Esto debería permitirle comparar fechas sin la hora.

 0
Author: Adam Robinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-03-25 19:23:46
        int o1 = date1.IndexOf("-");
        int o2 = date1.IndexOf("-",o1 + 1);
        string str11 = date1.Substring(0,o1);
        string str12 = date1.Substring(o1 + 1, o2 - o1 - 1);
        string str13 = date1.Substring(o2 + 1);

        int o21 = date2.IndexOf("-");
        int o22 = date2.IndexOf("-", o1 + 1);
        string str21 = date2.Substring(0, o1);
        string str22 = date2.Substring(o1 + 1, o2 - o1 - 1);
        string str23 = date2.Substring(o2 + 1);

        if (Convert.ToInt32(str11) > Convert.ToInt32(str21))
        {
        }
        else if (Convert.ToInt32(str12) > Convert.ToInt32(str22))
        {
        }
        else if (Convert.ToInt32(str12) == Convert.ToInt32(str22) && Convert.ToInt32(str13) > Convert.ToInt32(str23))
        {
        }
 -17
Author: Hetuk Upadhyay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-19 14:51:07