1

I have created a function that I feed a quarter (1, 2, 3 or 4) and a year (for example 2014). This function then calculates the first and the last day of this quarter.

It works fine sometimes, but when I feed quarter "4", I get an argument-out-of-range-exception in this line:

Dim dtLastDay As New DateTime(uYear, 3 * uQuarter + 1, 1)

I am not sure why this happens. Can somebody help?

Thank you very much!

Public Sub QuarterYearToDates(ByVal uQuarter As Integer, ByVal uYear As Integer, ByRef uStart As Date, ByRef uEnd As Date)

        Dim iMonth As Integer
        If uQuarter = 1 Then
            iMonth = 1
        ElseIf uQuarter = 2 Then
            iMonth = 4
        ElseIf uQuarter = 3 Then
            iMonth = 7
        ElseIf uQuarter = 4 Then
            iMonth = 10
        End If

        Dim dtFirstDay As New DateTime(uYear, 3 * uQuarter - 2, 1)
        Dim dtLastDay As New DateTime(uYear, 3 * uQuarter + 1, 1)
        dtLastDay = dtLastDay.AddDays(-1)

        uStart = dtFirstDay
        uEnd = dtlastday

    End Sub
tmighty
  • 10,734
  • 21
  • 104
  • 218

2 Answers2

3

When you pass that value, it evalutes to 13, and there is no 13th month.

You could handle this instead by using:

uEnd = dtFirstDay.AddMonths(3).AddDays(-1)

The DateTime.AddMonths method will handle this correctly for you.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

Order of operations for (3 * uQuarter + 1) is

( 3 * 4 ) + 1

or 13. There is no month 13.

ps2goat
  • 8,067
  • 1
  • 35
  • 68
  • If uQuarter is 4, then `3 * (uQuarter + 1)` will evaluate to 15 which is also a bad value for month. Perhaps the expression should be `3 * (uQuarter - 1)` – Chris Dunaway Jan 14 '14 at 15:48
  • good point =/ removed my example, since @ReedCopsey has the better code. – ps2goat Jan 14 '14 at 15:50