1

this might be helpful for some, but I also feel like it might be able to be improved upon or simplified. I have a recurring email campaign once a month that offers a new promotion for the course of the month. I didn't want to continuously update it so I wrote some code to handle it. The only issue is that every four years we have a leap year and not all months have the same amount of days. So this is what I've got in the AMPScript:

%%[

SET @monthOf = Format(now(),"MMMM")
SET @monthNumber = Format(now(),"MM")
SET @yearOf = FormatDate(now(),"YYYY")

SET @monthEndDate = ""
IF @monthNumber == 01 OR 
   @monthNumber == 03 OR 
   @monthNumber == 05 OR 
   @monthNumber == 07 OR 
   @monthNumber == 08 OR 
   @monthNumber == 10 OR 
   @monthNumber == 12 THEN
  SET @monthEndDate = 31
ELSEIF @monthNumber == 02 AND @yearOf == 2020 THEN
  SET @monthEndDate = 29
ELSEIF @monthNumber == 02 AND @yearOf != 2020 THEN
  SET @monthEndDate = 28
ELSE
  SET @monthEndDate = 30
ENDIF

]%%

I then call this later within the email text that states the start date and end date of the month.

Offer valid %%=v(@monthNumber)=%%/01 - %%=v(@monthNumber)=%%/%%=v(@monthEndDate)=%%.

This is the date format that is requested of me, so I cannot modify the way the date is displayed. If this is the best way to achieve this, great, but if there is a way to modify this to be better I'd be interested in learning it. If this helps someone else as well, excellent! Thanks!

2

I would recommend doing it like below instead:

%%[
SET @now = now()
SET @newDate = DATEADD(@now,1,"M")
SET @nextMonth = DatePart(@newDate,"M")
SET @day = 1
SET @year = DatePart(@newDate,"Y")
SET @newFirstDate = DateParse(CONCAT(@year,'-',@nextMonth,'-',@day))
SET @expireDate = DATEADD(@newFirstDate,-1,"D")
]%%
%%=v(@expireDate)=%%

This way by moving it to the next month (via DateAdd) you can make sure to get the correct year and correct date syntax. You then rebuild the date into the first of the next month (See @newFirstDate) and then do a dateadd() to remove one day from it. This will then provide you with the last day of the current month.

e.g. Output of above on today (10/15/2020) is:

10/31/2020

This should remove any worries about how many days are in a month and any issues around Leap Years as that is accounted for in the DateAdd function.

1
  • 1
    Gortonington - this is a great idea! Thank you for your response! Hopefully this can be helpful for others out there as well who might have a similar ask from their partners/company. I'm new but still upvoted (doesn't show) and accepted this as the answer. Thanks again. – Eduardo Oct 15 '20 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.