Search code examples
vbscriptasp-classic

How to get month name 12 months back with asp classic?


I want to display the short name for each month, 12 months back from the previous month, but with the below I get an error on mon1 and mon2 and I guess since that is last year?

    mon1=MonthName(Month(Now())-11,1)
    mon2=MonthName(Month(Now())-10,1)
    mon3=MonthName(Month(Now())-9,1)
    mon4=MonthName(Month(Now())-8,1)
    mon5=MonthName(Month(Now())-7,1)
    mon6=MonthName(Month(Now())-6,1)
    mon7=MonthName(Month(Now())-5,1)
    mon8=MonthName(Month(Now())-4,1)
    mon9=MonthName(Month(Now())-3,1)
    mon10=MonthName(Month(Now())-2,1)
    mon11=MonthName(Month(Now())-1,1)
    mon12=MonthName(Month(Now()),1)

So how can I display now,dec,jan,feb,mar,apr,may,jun,jul,aug,sep,oct Thanks.


Solution

  • The problem here is the Month() function returns an integer between 1 and 12 to represent each month. Instead you want to minus the number of months from the Now() value before wrapping it with Month().

    Below is an example that does this using a For loop and a single dimension Array.

    Dim dt: dt = Now()
    Dim i, mon(12)
    Const numOfMonths = 12
    
    For i = 1 To numOfMonths
      mon(i) = MonthName(Month(DateAdd("m", i - numOfMonths, dt)), True)
    Next
    
    Call Response.Write(Join(mon, vbCrLf))
    

    Output:

    Sep
    Aug
    Jul
    Jun
    May
    Apr
    Mar
    Feb
    Jan
    Dec
    Nov
    Oct