I got two dates, how do I check if both dates does not exceed over one year?
Short question! :-)
I got two dates, how do I check if both dates does not exceed over one year?
Short question! :-)
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))
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 );
TimeSpan ts = Date1.Subtract(Date2);
if(ts.Days > 365)
{
// Over a year.
}
That depends on the date format.
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;
}
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;
}
Takes into account leap years, etc.
if ( Math.Abs((d1 - d2).TotalDays)
<= Math.Abs((new DateTime(d1.Year, 1, 1)
- new DateTime(d2.Year, 1, 1)).TotalDays))
{
// Within 1 year
}