2013-03-15 71 views
0

我正在使用DateAdd函數將年添加到我現有的日期,但我想要去特定月份的最後日期。Vb.net添加年,然後去月的最後一天

我使用這個代碼:

Dim wr As Integer = Val(txtWar_per.Text) 
    Dim ins_dt As Date = dtpInstall.Value 
    Dim war_till As Date = DateAdd(DateInterval.Year, wr, dtpInstall.Value) 
    dtpWar_till.Value = war_till 

輸出:

dtpinstall.value= 12/1/2012 

txtWar_per.text= 2 

dtpWar_till.value=12/1/2014 

但我想dtpWar_till.value爲:

31/1/2014 

請儘早解決我的問題.. 非常,非常非常緊急。

+0

如果什麼ins_dt是2011年2月28日或2012年2月29日?無論何時,您都在使用日期測試飛躍值。 – dbasnett 2013-03-15 12:40:15

+0

嗨..我檢查了閏年,但如何2實現它?代碼即時使用即使閏年給予第28十二..代碼: 如果Date.IsLeapYear(war_till.Year)= True然後 'dtpWar_till.Value =新日期時間(ins_dt.Year + wr,ins_dt.Month,DateTime.DaysInMonth (ins_dt.Year,ins_dt.Month)) Else dtpWar_till.Value = New DateTime(ins_dt.Year + wr,ins_dt.Month,DateTime.DaysInMonth(ins_dt.Year,ins_dt.Month)) End If請提示代碼評論線。 – Harabati 2013-03-29 05:45:55

+0

我添加了一個可能有幫助的答案。 – dbasnett 2013-03-29 14:53:05

回答

0

測試使用閏年

Dim tstDate1 As Date = #2/28/2011# 
    Dim tstDate2 As Date = #2/29/2012# 

    For numYears As Integer = 1 To 5 
     'add years and set date to the first day of the month 
     Dim newD As Date = New Date(tstDate1.Year + numYears, tstDate1.Month, 1) 
     'then add days in month-1 to date 
     newD = newD.AddDays(Date.DaysInMonth(newD.Year, newD.Month) - 1) 
     'show it 
     Debug.WriteLine(newD) 


     newD = New Date(tstDate2.Year + numYears, tstDate2.Month, 1) 
     newD = newD.AddDays(Date.DaysInMonth(newD.Year, newD.Month) - 1) 
     Debug.WriteLine(newD) 
    Next 
+0

對我來說看起來像是一種矯枉過正,與此處提供的其他解答相比。 – Neolisk 2013-03-30 13:55:44

+0

只是試圖說明閏年沒有被考慮在答案中。我upvoted你的修改答案。 – dbasnett 2013-03-30 15:00:36

+0

解決海報問題的實際代碼只有兩行。 – dbasnett 2013-04-09 13:10:47

2

減去日期減去一個獲得該月的第一天,加一年零一個月,然後減去一天前一個月的最後一天:

Dim war_till As Date = ins_dt.AddDays(1 - ins.dt.Day).AddMonths(13).AddDays(-1) 

減少天數的兩倍,使確定它可以在不同天數的月份內工作,例如從2013-01-30到2014-01-31,而不是2014-03-01。

+0

非常感謝Guffa爲我們提供的幫助... – Harabati 2013-03-25 07:17:01

0

嘗試:

Dim war_till As Date = DateAdd(DateInterval.Day,-1,DateAdd(DateInterval.Month,2,DateAdd(DateInterval.Year, wr, dtpInstall.Value))) 
+0

非常感謝.. – Harabati 2013-03-25 07:25:02

1

一點點的代碼,卻多了幾分直觀:

Dim year As Integer = ins_dt.Year + wr 
Dim month As Integer = ins_dt.Month 
dtpWar_till.Value = New DateTime(year, month, DateTime.DaysInMonth(year, month))