Tutorial :Two dates within a year of each other



Question:

I got two dates, how do I check if both dates does not exceed over one year?

Short question! :-)


Solution:1

if (Math.Abs((d1 - d2).TotalDays) < 365)  

Edit: This should account for leap years better.

if ( d1 <= d2 && d1.AddYears(1) >= d2 || d2 < d1 && d2.AddYears(1) > d1)  

Update:
I like @JDunkerley's solution better:

if (d1 < d2 ? d2 < d1.AddYears(1) : d1 < d2.AddYears(1))   


Solution:2

I give you a little example:

DateTime startTime = DateTime.Now;     DateTime endTime = DateTime.Now.AddSeconds( 75 );     TimeSpan span = endTime.Subtract ( startTime );   Console.WriteLine( "Time Difference (seconds): " + span.Seconds );   Console.WriteLine( "Time Difference (minutes): " + span.Minutes );   Console.WriteLine( "Time Difference (hours): " + span.Hours );   Console.WriteLine( "Time Difference (days): " + span.Days );  


Solution:3

TimeSpan ts = Date1.Subtract(Date2);    if(ts.Days > 365)  {  // Over a year.  }  


Solution:4

That depends on the date format.

  • If you have two timestamps, you may calculate the difference between them.
  • If you have two specific dates in a known format, you simply compare the year attributes as strings.


Solution:5

If they're both in DateTime structures, then you can just subtract the two to get a Timespan structure. The Timespan structure has a Days property which you can look at.

So you'll have something like:

if(Math.Abs((date1 - date2).Days) <= 365) ...  


Solution:6

If necessary, swap t1 and t2 so that t1 <= t2

if(t1.AddYears(1) >= t2) {      // t1 is within a year of t2      return true;  } else {      // t1 is not within a year of t2      return false;  }  


Solution:7

This is the same question as "how do I calculate someone's age".

Blatantly stealing the answer from there and modifying it for use:

public static bool DatesAreWithinOneYear(DateTime date1, DateTime date2)  {      DateTime startDate = date2 > date1 ? date1 : date2;      DateTime endDate = date2 > date1 ? date2 : date1;        int years = endDate.Year - startDate.Year;      if (endDate < startDate.AddYears(years))      {          years--;      }      return years < 1;  }  


Solution:8

if (year(date1) == year(date2))  {     //true  }  else  {     //false  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »