Home > Net >  Set Date in VBScript for Date object without Time on format YYYYMMDD
Set Date in VBScript for Date object without Time on format YYYYMMDD

Time:10-02

I got the problem in VBScript when I try the set the Date (excluding Now) using the format YYYYMMDD

I need extract the date two days ago compared to today's date.

Using the following code I expect (for today's date) to have it out 20210929.

Instead I have 202110-1

enter image description here

My code below

   MyDate = Right(Year(DateSerial(Year(Date),Month(Date),1)),4) &_
            Right(String(2, "0") &_
            Month(DateSerial(Year(Date),Month(Date),1)), 2) &_
            Right(String(2, "0") & Day(Now) -2, 2)

   MsgBox(MyDate)
   WScript.quit  

Thanks

Update #01

   MyDate = Right(Year(DateSerial(Year(Date),Month(Date),1)),4) &_
            Right(String(2, "0") &_
            Month(DateSerial(Year(Date),Month(Date),1)), 2) &_
            Right("00" & DateAdd("d", -2, Day(Now)), 2)

   MsgBox(MyDate)
   WScript.quit  

Output 20211099

CodePudding user response:

Do the day subtraction first and then do the formatting, like this:

SetLocale("en-US")
TwoDaysAgo = DateSerial(Year(Now), Month(Now), Day(Now) - 2)
ArrD = Split(TwoDaysAgo,"/")
ymd = ArrD(2) & Right("0" & ArrD(0), 2) & Right("0" & ArrD(1), 2) 
MsgBox ymd
  • Related