Given a DateTime
object, i'd like to know which day of it's respective quarter it is.
E.g. 2 Feb
is 33
rd day of 1st quarter.
I can get the quarter from the month like so:
(int)System.Math.Ceiling(month / (double)3)
I can also use DateTime.DaysInMonth()
to find out how many days were in each of the quarters.
I wrote this particularly unsightly method, was hoping someone can point me to (something obvious) i am sure i am missing.
public static int DayOfQuarter(DateTime dt)
{
var quarter = GetQuarter(dt);
int[] months = new int[0];
switch (quarter)
{
case 1:
months = new[] { 1, 2, 3 };
break;
case 2:
months = new[] { 4, 5, 6 };
break;
case 3:
months = new[] { 7, 8, 9 };
break;
case 4:
months = new[] { 10, 11, 12 };
break;
}
var idx = -1;
for (var i = 0; i < months.Length; i++)
{
if (months[i] == dt.Month)
{
idx = i;
}
}
if (idx == 0)
{
return dt.Day;
}
if (idx == 1)
{
return DateTime.DaysInMonth(dt.Year, dt.Month - 1) + dt.Day;
}
return DateTime.DaysInMonth(dt.Year, dt.Month - 2) + DateTime.DaysInMonth(dt.Year, dt.Month - 1) + dt.Day;
}