How to compare only Date without Time in DateTime types?
Asked Answered
T

12

409

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?

Thera answered 25/3, 2009 at 19:17 Comment(0)
F
697

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

if(dtOne.Date == dtTwo.Date)
    ....
Fransen answered 25/3, 2009 at 19:19 Comment(7)
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.Complicate
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.Sawyere
This is absolutely NOT the correct answer. The OP specifically said Linq to SQL and datetime.date is NOT allowed in linq expressions.Camacho
@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.Kufic
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 workVaginitis
If you end up here sometimes after late 2021 looking for confirmation on this answer. It does work.Aldoaldol
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.Myungmyxedema
M
68

For a true comparison, you can use:

dateTime1.Date.CompareTo(dateTime2.Date);
Momus answered 25/3, 2009 at 19:20 Comment(12)
doesn't "==" return the results from CompareTo internally?Kilauea
What exactly do you mean by "true comparison"?Thaddeus
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.Momus
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.Momus
@ReedCopsey Can't you just use (dateTime1.Date < dateTime1.Date)?Extend
@Extend Not if you want a comparison - a comparison (in .NET terms) will return -1/0/1 depending on the values.Momus
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 @Extend that it is much more natural to use dateTime1.Date < dateTime1.Date, and similarly with <=, > and >=, in most applications.Contradiction
@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.Momus
Just looked this up. DateTimes == compares the number of Ticks of the two objects (or rather structs) so CompareTo would seem unnecessary here. see msdnHowland
@BjörnAliGöransson That's equality, not comparison... comparison returns -1/0/1, not true/false.Momus
@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)Howland
This wont work as it still compares the time value. See TruncateTime.Battled
C
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)

Courteous answered 17/2, 2014 at 9:30 Comment(2)
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..Oruro
According to this thread this is no longer needed in EF CoreLenity
F
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));
Fellows answered 4/4, 2016 at 23:2 Comment(3)
Just a reminder here: As long as it is Linq to Entity.Faithfaithful
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?!).Camacho
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)Queue
A
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....");
}
Anastase answered 26/5, 2012 at 11:6 Comment(0)
J
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.

Josuejosy answered 10/3, 2016 at 13:53 Comment(2)
This doesn't answer the question how to do it in Entity Framework.Broomrape
The question mentions DateTime but nothing about EF, so this answer is perfectly validKarns
R
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
   }
Reisinger answered 30/6, 2014 at 12:27 Comment(0)
A
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.

Audio answered 23/8, 2013 at 14:50 Comment(0)
R
2

You can try

if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
  ....
Rahm answered 13/2, 2020 at 15:20 Comment(0)
A
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);
Afterburning answered 7/4, 2021 at 0:37 Comment(0)
M
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.

Melvinmelvina answered 25/3, 2009 at 19:23 Comment(0)
O
-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))
        {
        }
Origan answered 19/10, 2011 at 14:51 Comment(2)
-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.Elwina
No need to create this much variables as it increase response time for such a easy task.Lousy

© 2022 - 2024 — McMap. All rights reserved.