426

Is there a way to compare two DateTime variables but to disregard the Time part.

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:34 and 12/3/89 11:22:12 and have it disregard the actual time of day so both of these are considered the same.

I guess I can set all the times of day to 00:00:00 before 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.

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?

13 Answers 13

717

try using the Date property on the DateTime Object...

if(dtOne.Date == dtTwo.Date)
    ....
Sign up to request clarification or add additional context in comments.

7 Comments

If you end up here sometime after early 2017 looking for a way to compare dates in an Entity Framework environment like I did check out the answer below by Alejandro and the comment by wasatchWizard.
If you end up here sometime after mid 2018 looking for a way to read another extremely helpful comment like the one above, you're out of luck.
This is absolutely NOT the correct answer. The OP specifically said Linq to SQL and datetime.date is NOT allowed in linq expressions.
@Mr.Ott 2021 here. Jan 20, USA (inauguration day) 4,367 Covid-19 deaths. But yeah good tip. For my purposes of filtering by date range, I had an issue because DateTime.Today uses time of 00:00:00 so I just used DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59) instead.
If you end up here sometimes after late 2021 looking for confirmation on this answer. It does work.
|
70

For a true comparison, you can use:

dateTime1.Date.CompareTo(dateTime2.Date);

12 Comments

What exactly do you mean by "true comparison"?
Randolpho: Using == will give you equality, so whether the two dates are the same or different. CompareTo will ~compare~ them, ie: give you a way in one pass to tell if date1>date2, date1<date2, or date1==date2.
@ReedCopsey Can't you just use (dateTime1.Date < dateTime1.Date)?
But who wants -1, 0 and 1, really? They are just magical numbers representing "less", "equal" and "greater". And you will have to "compare" the resulting integer to something afterwards because there are three possible values. I must agree with @David that it is much more natural to use dateTime1.Date < dateTime1.Date, and similarly with <=, > and >=, in most applications.
@JeppeStigNielsen If you're using this in anything that sorts or takes a comaprison, then you want it - otherwise, you typically just want the operators.
|
68

This is how I do this in order to work with 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.Date it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)

2 Comments

This works great with LINQ to Entities. However, EntityFunctions has been deprecated in .NET 4.5.2. Use this instead: DbFunctions.TruncateTime. It appears to be the identical method, just moved..
According to this thread this is no longer needed in EF Core
36

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

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

Example

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

3 Comments

Just a reminder here: As long as it is Linq to Entity.
This should be the correct answer (as of 2019). EntityFunctions is depreciated and you're not allowed to use datetime.date in a lambda expression (for whatever reason - I mean seriously... why haven't they fixed this?!).
This should be the accepted answer. Either that or possibly reset time on either side of the DateTime comparison. e.g. LHS <= RHS where LHS is startDateTime.Date (00:00 AM) and RHS is endDateTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59) (23:59:59 PM)
12
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....");
}

Comments

11
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.

2 Comments

This doesn't answer the question how to do it in Entity Framework.
The question mentions DateTime but nothing about EF, so this answer is perfectly valid
3
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
   }

Comments

2
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.

Comments

2

You can try

if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
  ....

Comments

2

In .NET 5:

To compare date without time you must use EF.Functions.DateDiffDay() otherwise you will be comparing in code and this means you are probably pulling way more data from the DB than you need to.

.Where(x => EF.Functions.DateDiffDay(x.ReceiptDate, value) == 0);

Comments

2

Since .NET 6, we have the DateOnly type, which only holds the date and can be used where applicable or even as a trick if you're willing to perform conversions. It’s not a universal solution, but it can be useful in some cases.

using System;
DateTime date = new(89, 3, 12, 12, 43, 34);
DateTime date2 = new(89, 3, 12, 11, 22, 12);
DateOnly d1 = new(date.Year, date.Month, date.Day);
DateOnly d2 = new(date2.Year, date2.Month, date2.Day);
Console.WriteLine(date == date2);
Console.WriteLine(d1 == d2);

See on .NET Fidlle. I put on Github to future reference.

Comments

1

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

Comments

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

2 Comments

-1: Why not just parse to DateTime and use @Quintin Robinson's method? This is code I would expect to see on the The Daily WTF.
No need to create this much variables as it increase response time for such a easy task.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.