3

I am trying to compare a DateTime variable with another DateTime variable and if they are with 24 hours of one another then do something. So for example,

if (todaysDate == OtherDate) 
{
//do stuff only if otherDate is within 24 hours of todaysDate
}

I understand I can use the operators found here, https://msdn.microsoft.com/en-us/library/ff986512(v=vs.110).aspx to compare the dates, but none of those comparisons seem to give me what I'm wanting so was curious how this might be accomplished.

Sunil
  • 3,404
  • 10
  • 23
  • 31
jelidens
  • 221
  • 1
  • 4
  • 14
  • 1
    You can use `Subtraction` operator. It will return the timespan. Then you can check the `TotalHours` property of TimeSpan to determine if the difference is 24 hours or less. https://msdn.microsoft.com/en-us/library/1905yhe2(v=vs.110).aspx – Chetan Apr 24 '18 at 03:10
  • 1
    Possible duplicate of [Calculate relative time in C#](https://stackoverflow.com/questions/11/calculate-relative-time-in-c-sharp) – Ken White Apr 24 '18 at 03:16
  • 1
    `if (Math.Abs((todaysDate - otherDate).TotalHours) <= 24) { }` – Rufus L Apr 24 '18 at 03:45
  • 1
    @RufusL personally I prefer `if((todaysDate - otherDate).Duration().TotalHours <= 24) { }` – Scott Chamberlain Apr 24 '18 at 03:51
  • 1
    @ScottChamberlain Well, now I do, too! :) – Rufus L Apr 24 '18 at 03:52

1 Answers1

6

Use Subtract method and TotalHours property.

System.DateTime date1 = new System.DateTime(2018, 4, 24, 22, 15, 0);
System.DateTime date2 = new System.DateTime(2018, 4, 24, 13, 2, 0);

System.TimeSpan diff1 = date2.Subtract(date1);

Console.WriteLine(diff1.TotalHours);

if(diff1.TotalHours >= -24 && diff1.TotalHours <=24)
{
    Console.WriteLine("Within +/- 24 Hours");
}
Sunil
  • 3,404
  • 10
  • 23
  • 31