-1

What would be the easiest way for me to assign my quarter end month based upon the month im in?

Is there something i can use like modulo? I want the simplest case and least amount of lines of code

My quarter ends months are months 3,6,9 and 12.

I want to avoid doing a logic like this:

if (1 <= mymonth && mymonth <= 3)
    mymonth = new DateTime(DateTime.Now.Year, 3, 15);
else if (4 <= mymonth && mymonth <= 6)
    mymonth = new DateTime(DateTime.Now.Year, 6, 15);
else if (7 <= mymonth && mymonth <= 9)
    mymonth = new DateTime(DateTime.Now.Year, 9, 15);
else
    mymonth = new DateTime(DateTime.Now.Year, 12, 15);
Martin Niederl
  • 649
  • 14
  • 32
abarz12
  • 27
  • 1
  • 4

3 Answers3

1

You can use:

var quarterEndMonth = 3 * Math.Ceiling((double)currentMonth / 3);

Demonstration

JLRishe
  • 99,490
  • 19
  • 131
  • 169
0

What about this?

public DateTime GetQuarterEnd(int month)
{
    if (month < 1 || month > 12)
        throw new ArgumentException("month is not a valid Month of the year.");

    var mod = month % 3;
    var actual = month / 3 + (mod > 0 ? 1 : 0);
    return new DateTime(DateTime.Now.Year, actual * 3, 15);
}
Barry O'Kane
  • 1,189
  • 7
  • 12
0

Least amount of lines could be something like this:

var d = new DateTime(DateTime.Now.Year, 3*(1+(mymonth-1)/3), 15);

But that is ugly as hell :)

https://dotnetfiddle.net/HZfFLF

Fortega
  • 19,463
  • 14
  • 75
  • 113