396

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?

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291
Sruly
  • 10,200
  • 6
  • 34
  • 39

12 Answers12

683

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

if(dtOne.Date == dtTwo.Date)
    ....
Quintin Robinson
  • 81,193
  • 14
  • 123
  • 132
  • 38
    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. – Mike Devenney Apr 13 '17 at 17:05
  • 14
    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. – nardnob Jun 01 '18 at 19:12
  • 4
    This is absolutely NOT the correct answer. The OP specifically said Linq to SQL and datetime.date is NOT allowed in linq expressions. – Philip Vaughn May 14 '19 at 19:54
  • @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. – codah Jan 22 '21 at 04:55
  • At first I thought this worked but it doesn't. When you have different "time of days" in your datetime object this solution does not work – Tekin Nov 15 '21 at 19:37
  • 1
    If you end up here sometimes after late 2021 looking for confirmation on this answer. It does work. – Neil Nov 19 '21 at 09:11
  • The comment on MSDN for the 'Date' property says "A new object with the same date as this instance, and the time value set to 12:00:00 midnight (00:00:00)." And the operator for '==' is implemented like this: (DateTime d1, DateTime d2) => d1.InternalTicks == d2.InternalTicks. Thats is why the answer seems perfectly okay to me. – Martin Dec 30 '21 at 13:13
67

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)

Alejandro del Río
  • 3,966
  • 3
  • 33
  • 31
  • 34
    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.. – kodybrown Apr 12 '16 at 18:17
  • According to [this thread](https://stackoverflow.com/questions/40758784/dbfunctions-truncatetime-linq-equivalent-in-ef-core) this is no longer needed in EF Core – Bernard Borg Mar 01 '23 at 17:32
66

For a true comparison, you can use:

dateTime1.Date.CompareTo(dateTime2.Date);
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • doesn't "==" return the results from CompareTo internally? – Steven Evers Mar 25 '09 at 19:28
  • 22
    What exactly do you mean by "true comparison"? – Randolpho Mar 25 '09 at 19:29
  • SnOrfus: Not always. Many implementations return a.CompareTo(b)==0 for ==, but that's up to the implementation. I haven't checked DateTime's internal implemetnation of equality. – Reed Copsey Mar 25 '09 at 19:38
  • 7
    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 – Reed Copsey Mar 25 '09 at 19:38
  • 8
    @ReedCopsey Can't you just use (dateTime1.Date < dateTime1.Date)? – David Mar 07 '14 at 09:13
  • 1
    @David Not if you want a comparison - a comparison (in .NET terms) will return -1/0/1 depending on the values. – Reed Copsey Mar 07 '14 at 19:34
  • 22
    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. – Jeppe Stig Nielsen Mar 11 '14 at 09:44
  • 9
    @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. – Reed Copsey Mar 11 '14 at 17:34
  • 1
    Just looked this up. `DateTime`s `==` compares the number of `Ticks` of the two objects (or rather `structs`) so `CompareTo` would seem unnecessary here. [see msdn](https://msdn.microsoft.com/en-us/library/system.datetime.op_equality(v=vs.110).aspx?f=255&mspperror=-2147217396#Anchor_1) –  Feb 15 '17 at 21:13
  • 1
    @BjörnAliGöransson That's equality, not comparison... comparison returns -1/0/1, not true/false. – Reed Copsey Feb 15 '17 at 23:23
  • 1
    @ReedCopsey I strongly believe that the OP is using "comparison" in the sense of "equality comparison" (just looked it up, the word is actually in the [msdn](https://msdn.microsoft.com/en-us/library/dd183752.aspx)) –  Feb 16 '17 at 12:00
  • This wont work as it still compares the time value. See TruncateTime. – Kim Mar 31 '20 at 19:38
35

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));
Korayem
  • 12,108
  • 5
  • 69
  • 56
  • Just a reminder here: As long as it is Linq to Entity. – curiousBoy Mar 15 '18 at 23:27
  • 1
    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?!). – Philip Vaughn May 14 '19 at 19:56
  • 1
    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)** – om-ha Feb 03 '21 at 22:20
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....");
}
Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
Devarajan.T
  • 119
  • 1
  • 3
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.

Code Geek
  • 143
  • 1
  • 6
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
   }
Mohan Sharma
  • 180
  • 7
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.

LarsTech
  • 80,625
  • 14
  • 153
  • 225
dgsjr
  • 21
  • 1
2

You can try

if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
  ....
Cristian
  • 23
  • 4
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);
Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
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.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
-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))
        {
        }