Harabati
Harabati

Reputation: 133

Vb.net Add years and then go to last day of the month

I am using DateAdd function to add years to my existing date but I want to go to last date of that specific month.

I am using this code:

    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

Output:

dtpinstall.value= 12/1/2012

txtWar_per.text=  2

dtpWar_till.value=12/1/2014

But I want dtpWar_till.value as:

31/1/2014

Please resolve my problem early.. It's very, very, very urgent.

Upvotes: 0

Views: 3815

Answers (4)

Victor Zakharov
Victor Zakharov

Reputation: 26424

A little bit more code, but somewhat more intuitive:

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))

Upvotes: 1

dbasnett
dbasnett

Reputation: 11773

Test using leap years

    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

Upvotes: 0

Guffa
Guffa

Reputation: 700322

Subtract the date minus one to get to the first day of the month, add a year and a month, then subtract another day to the last day of the previous month:

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

Subtracting days twice makes sure that it works with months with different number of days, e.g. from 2013-01-30 takes you to 2014-01-31 rather than 2014-03-01.

Upvotes: 2

Neil Mussett
Neil Mussett

Reputation: 708

Try:

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

Upvotes: 0

Related Questions