I'm trying to come up with a more elegant solution for a loop in months that I wrote long time ago in C# 1.1
I use a helper class Month but I'd prefer to get rid of it and make the code shorter and more readable.
I receive a start period in format yyyy-mm and end period yyyy-mm and I need to execute something for every month between those 2 periods.
public void LoopMonths(string startM, string endM)
{
//startM = "2015-02";
//endM = "2018-11";
int startYear = int.Parse(startM.Split('-')[0]);
int startMonth = int.Parse(startM.Split('-')[1]);
int endYear = int.Parse(endM.Split('-')[0]);
int endMonth = int.Parse(endM.Split('-')[1]);
Month month = new Month(startYear, startMonth);
Month monthEnd = new Month(endYear, endMonth);
while (month <= monthEnd)
{
// do something ...
month = Month.NextMonth(month);
}
}
public class Month
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public Month(int year, int month)
{
StartDate = new DateTime(year, month, 1);
EndDate = new DateTime(year, month, DateTime.DaysInMonth(year, month));
}
public static Month NextMonth(Month month)
{
DateTime next = month.StartDate.AddMonths(1);
return new Month(next.Year, next.Month);
}
public static bool operator <=(Month month1, Month month2)
{
return month1.StartDate <= month2.StartDate;
}
public static bool operator >=(Month month1, Month month2)
{
return month1.StartDate >= month2.StartDate;
}
}
Month
as an enum (Jan, Feb, ...), but OP is thinking of month as part of a date value. Either can be correct. I'd expect your interpretation to be an enum, not a class. \$\endgroup\$Month
object refers to one month (of a particular year). In order to define a range (since you claim "Month
spans years"),Month
would have to have two year values (begin and end of the range), which it simply doesn't. It only has one month value, one year value. I think you're getting confused by theStartDate
/EndDate
properties: the properties could technically span years; but the existing logic simply doesn't do that (it sets both properties to the same month, same year, but a different day). \$\endgroup\$Month
object contain more than the defined month. At no point is aMonth
object ever defined to refer to more than one month. If you want to claim thatMonth
can span years, I'm interested in hearing your proof of that. Substantiate your claims. \$\endgroup\$