HaySeed
HaySeed

Reputation: 137

Determine current year or previous year based upon month selection

I have inherited an archive program written in C#. The previous developer was only interested in archiving data from the previous month. However, some months were missed and my task had been to add functionality to see what other months were missed.

The part I am stuck on is: When determining the missed month, I need to determine if the month is part of the current year or is it from the previous year.

The current month is the key. If the current month is Sept, then months from Jan to Sept are considered current year.

If the current month is Sept, then Oct to Dec are considered the previous year. Of course, this would be a sliding range as each month progressed.

Looking for some guidance.

Upvotes: 3

Views: 15422

Answers (3)

Bryan Crosby
Bryan Crosby

Reputation: 6554

You can get the current month number (via DateTime.Month) and subtract it from the comparison month and check if it's greater than zero.

Sample:

int month1 = 5;  //may
int month2 = 4;  //apr
bool isCurrentYear = (month1 - month2 >= 0);  //current year

int month1 = 8;  //aug
int month2 = 11;  //nov
bool isCurrentYear = (month1 - month2 >= 0); //last year

Upvotes: 0

BigL
BigL

Reputation: 1631

Use DateTime.Now.Month it gives you the actual Month and you can compare to that the other dates you have as you described if it is smaller or equal then it is current year if it is greater then previous year.

And then you can set the archive date on a previous year archive with DateTime.Now.AddYears(-1)

Upvotes: 1

Brandon
Brandon

Reputation: 69973

Unless I'm missing something, you just need to compare your missing month date against DateTime.Today.Month

DateTime archiveDate;
if(someMonth > DateTime.Today.Month)
    archiveDate = new DateTime(DateTime.Today.Year - 1, someMonth, 1);
else
    archiveDate = new DateTime(DateTime.Today.Year, someMonth, 1);

Upvotes: 6

Related Questions