There are two variables that store a DateTime value. How can you compare for equality taking to account only the hours and minutes. In addition to this option:

date1.Hours == date2.Hours && date1.Minutes == date2.Minutes 
  • 2
    10:10:59 and 10:11:01 should be equal (between them where less than a minute) or not (the number of whole minutes is not equal)? - Akina
  • Not equal. Yes, the number of whole minutes. - Alexander Puzanov
  • In fact, the difference in minutes between two dates will solve my problem. - Alexander Puzanov
  • In addition to this option, you can arrange this option as an int сравнить_до_минут(Date a, Date b) function, and using this function if (сравнить_до_минут(date1, date2) < 0) ... , no longer worry about the ugly condition :) - Sergey
  • 3
    Well, how should one think in order to issue two mutually exclusive comment-answers in a row? - Akina

3 answers 3

 Int64 t1 = (Int64) TimeSpan.FromTicks(date1.Ticks).TotalMinutes; Int64 t2 = (Int64) TimeSpan.FromTicks(date2.Ticks).TotalMinutes; return t1 == t2; 

    If the difference between the dates in minutes solves the problem - then here's the code:

     Math.Abs((date1 - date2).TotalMinutes) < 1 

    But such a date comparison will be non-transitive: 00:00:10 will be 00:00:40, and 00:00:40 will be 00:01:10 - but 00:00:10 is not equal to 00:01:10.

    To preserve transitivity, it is better to discard the lower parts of the date:

     DateTime TruncateToMinutes(DateTime date) => new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, 0); TruncateToMinutes(date1) == TruncateToMinutes(date2); 

      You can convert both DateTime variables to the Unix Timestamp, for example, as shown here , using only hours and minutes, as you want, and then compare the 2 resulting Timestamps.