2014-01-13 24 views
1

我創建了一個函數,我提供了一個季度(1,2,3或4)和一年(例如2014)。 這個函數然後計算本季度的第一天和最後一天。VB.NET DateTime OutOfRangeException

有時候工作正常,但是當我喂季度「4」,我得到一個說法,超出範圍的異常在這一行:

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

我不知道爲什麼會這樣。 有人可以幫忙嗎?

非常感謝!對於(3 * uQuarter + 1)操作的

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 
+0

學習使用調試器,它可以在這種情況和類似情況下提供幫助。 – Neolisk

+0

你可能會覺得這個答案有幫助:http://stackoverflow.com/a/568122/897326 – Neolisk

+1

你已經用'iMonth'完成了本季度的最初一個月。你有沒有使用它的原因? –

回答

3

當您通過那價值,它評估到13,並且沒有13個月。

你可以使用,而不是處理這個問題:

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

DateTime.AddMonths方法將正確處理此爲您服務。

+0

這真的是一些漂亮的代碼! – tmighty

2

秩序是

(3 * 4)+ 1

或13沒有月13

+0

如果uQuarter是4,那麼'3 *(uQuarter + 1)'將評估爲15,這在月份也是一個不好的值。也許表達式應該是'3 *(uQuarter - 1)' –

+0

好點= /刪除我的例子,因爲@ReedCopsey有更好的代碼。 – ps2goat