Format the date of the previous day format yyyymmd

2019-08-28 05:58发布

问题:

This question already has an answer here:

  • VBScript How can I Format Date? 6 answers
  • Format current date and time in VBScript 1 answer

I need format the date of the previous day in this format, with VBScript :

yyyymmdd

And I have tried this solution :

NewData = 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(DateAdd("d",-1, Now())), 2)  

But instead of getting :

20190630

I have :

20190730

Can you help me ?

Thanks in advance for any help.

回答1:

You should first store yesterday in a variable and then do your formatting magic on this date.

dim yesterday
yesterday = DateAdd("d",-1, Now())
NewData = Right(Year(DateSerial(Year(yesterday),Month(yesterday),1)),4) _
        & Right(String(2, "0") _
        & Month(DateSerial(Year(yesterday),Month(yesterday),1)), 2) _
        & Right(String(2, "0") & Day(yesterday), 2) 

I strongly suspect there are more straightforward ways to get a date in format YYYYMMDD however.