1.

Solve : DATE ADD VBSCRIPT?

Answer»

Hey ,

I have written this VB script to add a MONTH to the last day of the current month and get the last day of the next month.
Issue: If the current month has 30 days then the script is returning me 30 days for the next month as well.


Vbscript:

strDate = WScript.Arguments.Item(0)
dtmDateYr = LEFT(strdate,4)
dtmDateMn1 = left(strdate,6)
dtmDateMn = right(dtmDateMn1,2)
dtmDateDy = right(strdate,2)
dtmDate = dtmDateMn &"/"& dtmDateDy &"/"& dtmDateYr
wscript.echo dtmDate
tomDate = DateAdd("m", 1,dtmDate)
wscript.echo tomDate

If Month(tomDate) < 10 Then
   If Day(tomDate) < 10 Then
      tomDate1 = Year(tomDate) & "0" &Month(tomDate) &"0"& Day(tomDate)
      Wscript.Echo ""& Year(tomDate) & "0" &Month(tomDate) &"0"& Day(tomDate)
      
   Else
      tomDate1 = Year(tomDate) & "0" &Month(tomDate) &Day(tomDate)
      Wscript.Echo ""& Year(tomDate) & "0" &Month(tomDate) &Day(tomDate)
   End If   
Else
   If Day(tomDate) < 10 Then
      tomDate1 = Year(tomDate) &Month(tomDate) &"0"& Day(tomDate)
      Wscript.Echo ""& Year(tomDate) &Month(tomDate) &"0"& Day(tomDate)
   Else
      tomDate1 = Year(tomDate) &Month(tomDate) &Day(tomDate)
      Wscript.Echo ""& Year(tomDate) &Month(tomDate) &Day(tomDate)
   End If   
End If

Set myFSO = CreateObject("Scripting.FileSystemObject")
Set WriteStuff = myFSO.OpenTextFile("C:\date\month\"&strDate&".txt", 8, True)
WriteStuff.WriteLine(tomDate1)
WriteStuff.Close
SET WriteStuff = NOTHING
SET myFSO = NOTHING




Looks like DateAdd function is not behaving properly.
Date FORMAT : yyyymmdd  example 20160831 or 20160930
If I am passing 20160930 I am expecting 20161031 and likewiseAdding a Month to SEPTEMBER 30th, 2016 gives you October 30th, 2016. It adds or subtracts 30 days and clamps it to the month if necessary, basically. It only changes the day portion when necessary to clamp within the month.

If you want to get the last day of a month,  you can use DateSerial. As DOCUMENTED, if you pass in a Day parameter of 0, it will return the last day of the previous month. For example:

Code: [Select]DateSerial(2016,11,0)

returns October 31st, 2016.



Discussion

No Comment Found