Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing integers that represent a date

I'm struggling with the logic to determine if a date is within 30 days of another date. What makes this tricky is that the dates are represented by integers. So if I have:

int year = 1990; int month = 1; int day = 1;

How can I correctly return true if I compare this with:

int year = 1989; int month = 12; int day = 31

currently I'm using DateTime.DaysInMonth(year, month) but not sure how to apply that in a comparison.

like image 999
Justiciar Avatar asked Jun 08 '26 04:06

Justiciar


1 Answers

I'd construct two DateTime objects and subtract them:

int year1 = 1990; 
int month1 = 1; 
int day1 = 1;
DateTime dt1 = new DateTime(year1, month1, day1);

int year2 = 1989; 
int month2 = 12; 
int day2 = 31;
DateTime dt2 = new DateTime(year2, month2, day2);

if ((dt2 - dt1).TotalDays <= 30) {
    Console.WriteLine("Dates are within 30 days of each other");
}
like image 133
Mureinik Avatar answered Jun 10 '26 18:06

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!