I'm trying to get the day of month for following calendar:
I wrote two different functions that accomplish this:
public int DayOfYear(int year, int month, int day)
{
var months = new[] {31, 31, 31, 31, 31, 30, 30, 30, 30, 30, 30, 31};
var dayOfYear = day;
if (month == 1) return dayOfYear;
for (var i = 0; i < month-1; i++)
{
dayOfYear += months[i];
}
return dayOfYear;
}
And to do this without a loop:
public int DayOfYear(int year, int month, int day)
{
var dayOfYear = day;
if (month <= 5)
dayOfYear += 31 * (month-1);
else
dayOfYear += 31 * 5 + 30 * ((month - 5) - 2);
if (month == 12)
dayOfYear += 31;
return dayOfYear;
}
For the 12th month lets assume it has always 31 days. I feel that there is a beter mathematical way of doing this, but I can't really come up with it.
An example: (522, 12, 14) is the 349th day of the year according to my calendar. This is correct using both functions. And (522, 1, 1) would be the first day of the year.
For some visualization, (522, 5, 18) would be done as following:
31 + 31 + 31 + 31 + 18
And (522, 9, 18) as:
31 + 31 + 31 + 31 + 31 + 30 + 30 + 30 + 18
