I tried to write a date 'add months' function.
I believe it works correctly, but it's not guaranteed,
so please mention any bugs if there are any.
Basically it will add months, maintaining the day of the month.
If the day of the month is too big for the month, the
day is adjusted downwards.
[EDIT:]
I just saw FanaticGuru's function, I had thought about
converting to months first, it looks like it's much simpler,
I will update my function I believe!
[EDIT 2: see improved version of code at the bottom of this post]
Code: Select all
q:: ;date add months
vDate := A_Now
vFormat := "HH:mm dd/MM/yyyy"
vNum := 3
vDate0 := JEE_DateAddMonths(vDate, 0, vFormat)
vDate1 := JEE_DateAddMonths(vDate, -vNum, vFormat)
vDate2 := JEE_DateAddMonths(vDate, vNum, vFormat)
MsgBox % vDate1 "`r`n" vDate0 "`r`n" vDate2
Return
;==================================================
JEE_DateAddMonths(vDate, vNum, vFormat="")
{
vDate += 0, Seconds ;make date the standard 14-character format
vYear := SubStr(vDate, 1, 4)
vMonth := SubStr(vDate, 5, 2)
vDay := SubStr(vDate, 7, 2)
vTime := SubStr(vDate, 9)
vSign := (vNum < 0) ? -1 : 1
vNum := Abs(vNum)
vYears := vSign*Floor(vNum/12)
vMonths := vSign*Mod(vNum,12)
if (vSign = -1) && (vMonth+vMonths < 1)
vYears -= 1, vMonths := 12+vMonths
if (vSign = 1) && (vMonth+vMonths > 12)
vYears += 1, vMonths := vMonths-12
vYear += vYears
vMonth += vMonths
if (vMonth = 2) && (vDay > 28)
if !Mod(vYear,4) && (Mod(vYear,100) || !Mod(vYear,400)) ;4Y AND (100N OR 400Y)
vDay := 29
else
vDay := 28
if (vDay = 31)
if vMonth in 4,6,9,11
vDay := 30
(StrLen(vMonth)=1) ? (vMonth := "0" vMonth) : ""
(StrLen(vDay)=1) ? (vDay := "0" vDay) : ""
vDate := vYear vMonth vDay vTime
if !(vFormat = "")
FormatTime, vDate, % vDate, % vFormat
Return vDate
}
[EDIT 2:]
improved version (simplified code):
Code: Select all
q:: ;date add months
vDate := A_Now
vFormat := "HH:mm dd/MM/yyyy"
vNum := 3
vDate0 := JEE_DateAddMonths(vDate, 0, vFormat)
vDate1 := JEE_DateAddMonths(vDate, -vNum, vFormat)
vDate2 := JEE_DateAddMonths(vDate, vNum, vFormat)
MsgBox % vDate1 "`r`n" vDate0 "`r`n" vDate2
Return
;==================================================
JEE_DateAddMonths(vDate, vNum, vFormat="")
{
vDate += 0, Seconds ;make date the standard 14-character format
vYear := SubStr(vDate, 1, 4)
vMonth := SubStr(vDate, 5, 2)
vDay := SubStr(vDate, 7, 2)
vTime := SubStr(vDate, 9)
vMonths := (vYear*12) + vMonth + vNum
vYear := Floor(vMonths/12)
vMonth := Mod(vMonths,12)
(!vMonth) ? (vYear -= 1, vMonth := 12) : ""
if (vMonth = 2) && (vDay > 28)
if !Mod(vYear,4) && (Mod(vYear,100) || !Mod(vYear,400)) ;4Y AND (100N OR 400Y)
vDay := 29
else
vDay := 28
if (vDay = 31)
if vMonth in 4,6,9,11
vDay := 30
(StrLen(vMonth)=1) ? (vMonth := "0" vMonth) : ""
(StrLen(vDay)=1) ? (vDay := "0" vDay) : ""
vDate := vYear vMonth vDay vTime
if !(vFormat = "")
FormatTime, vDate, % vDate, % vFormat
Return vDate
}