C# 如何仅将 Linq 中的 DateTime 类型中的 Date 与 SQL with Entity Framework 进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/683037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:16:39  来源:igfitidea点击:

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

c#.netdatabaseentity-frameworklinq-to-sql

提问by Sruly

Is there a way to compare two DateTimevariables in Linq2Sqlbut to disregard the Time part.

有没有办法比较两个DateTime变量,Linq2Sql但忽略时间部分。

The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.

该应用程序将项目存储在数据库中并添加发布日期。我想保留确切的时间,但仍然能够按日期本身提取。

I want to compare 12/3/89 12:43:34and 12/3/89 11:22:12and have it disregard the actual time of day so both of these are considered the same.

我想比较12/3/89 12:43:3412/3/89 11:22:12让它忽略一天中的实际时间,所以这两个被认为是相同的。

I guess I can set all the times of day to 00:00:00before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.

我想我可以00:00:00在比较之前设置一天中的所有时间,但实际上我确实想知道一天中的时间,我也希望能够仅按日期进行比较。

I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this?

我发现了一些具有相同问题的代码,它们分别比较了年、月和日。有一个更好的方法吗?

采纳答案by Quintin Robinson

try using the Dateproperty on the DateTimeObject...

尝试使用对象Date上的属性DateTime...

if(dtOne.Date == dtTwo.Date)
    ....

回答by Reed Copsey

For a true comparison, you can use:

要进行真正的比较,您可以使用:

dateTime1.Date.CompareTo(dateTime2.Date);

回答by Adam Robinson

In your join or where clause, use the Dateproperty of the column. Behind the scenes, this executes a CONVERT(DATE, <expression>)operation. This should allow you to compare dates without the time.

在您的 join 或 where 子句中,使用Date列的属性。在幕后,这会执行一个CONVERT(DATE, <expression>)操作。这应该允许您比较没有时间的日期。

回答by Hetuk Upadhyay

        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))
        {
        }

回答by Devarajan.T

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....");
}

回答by dgsjr

DateTime econvertedDate = Convert.ToDateTime(end_date);
DateTime sconvertedDate = Convert.ToDateTime(start_date);

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

The diff value represents the number of days for the age. If the value is negative the start date falls after the end date. This is a good check.

diff 值表示年龄的天数。如果值为负,则开始日期晚于结束日期。这是一个很好的检查。

回答by Alejandro del Río

This is how I do this in order to work with LINQ.

这就是我为了与 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));

If you only use dtOne.Date == dtTwo.Dateit wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)

如果您只使用dtOne.Date == dtTwo.Date它,则它不适用于 LINQ(错误:LINQ to Entities 中不支持指定的类型成员“日期”)

回答by Mohan Sharma

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
   }

回答by Code Geek

DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}

You can use this if you are using nullable DateFields.

如果您使用可为空的 DateFields,则可以使用它。

回答by Korayem

If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTimeIf you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime

如果您使用的是实体框架 < v6.0,则使用EntityFunctions.TruncateTime如果您使用的是实体框架 >= v6.0,则使用DbFunctions.TruncateTime

Use either (based on your EF version) around any DateTimeclass property you want to use inside your Linq query

围绕DateTime要在 Linq 查询中使用的任何类属性使用(基于您的 EF 版本)

Example

例子

var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate) 
                                       >= DbFunctions.TruncateTime(DateTime.UtcNow));