-1

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

  • 1
    `Day()` returns an integer, not a `Date()` so subtracting two (assuming today's date 01-Oct-2021) will give you `-1`. So, yes actually, if you had read the answer in the duplicate - "Returns a **whole number between 1 and 31**, inclusive, representing the day of the month. Passing Date() will return the current day of the month.". If you want to subtract from a date use `DateAdd("d", -2, Now())` instead. – user692942 Oct 01 '21 at 08:18
  • @user692942 thanks for reply. Please see **Update #01** in the question – Edward Sheriff Curtis Oct 01 '21 at 08:26

1 Answers1

2

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

d = DateAdd("d", -2, Now)
ymd = Year(d) & Right("0" & Month(d), 2) & Right("0" & Day(d), 2)
MsgBox ymd
LesFerch
  • 1,540
  • 2
  • 5
  • 21
  • No need for any of that, splitting on `/` is not recommended. Just needs to do the `DateAdd()` right before getting the `Day()` - Should have been `Right("00" & Day(DateAdd("d", -2, Now)), 2)`. – user692942 Oct 01 '21 at 16:45
  • Just tried that. Result was 20211029. Desired result is 20210929. – LesFerch Oct 02 '21 at 00:22
  • In which case just do the calculation first across the full date then break it up using `Year()`, `Month()` and `Day()`. – user692942 Oct 02 '21 at 01:47
  • 1
    Yup. Answer edited. – LesFerch Oct 02 '21 at 02:14
  • I'm not sure this need an answer as the duplicate answer (from 7 years ago) has a big bold box that says - "**IMPORTANT:** When formatting date / time values, always store the date / time value first. Also, any needed calculations (`DateAdd()` etc.) should be applied before attempting to format or you will get unexpected results.". Which is pretty much what the OP has done even though they denied the dup target solved their problem. – user692942 Oct 02 '21 at 12:43