4

To create an automated email program, I am performing some action based on the week of year. I am referencing the datepart() function, and want to convert NOW() into the current week of year - ie: Jan 15, 2019 --> 3.

I do not see documentation for native support of that conversion; so then I though to convert NOW() into current day of year - ie: Jan 15 2019 --> 15; Feb 1 --> 32 from which I could / 7 to get close to the week-of-year. I also don't see native support for this in ampscript.

As a workaround, I am generating the week-of-year in a tsql query while selecting subscribers in SFMC: DatePart(weekday, GETDATE()). This feels inefficient since it will generate the exact same value for every subscriber.

Has anyone encountered this problem before? What did you do? Am I missing something?

5

There is no premade function inside AMPscript to do this, but luckily with a bit of math you can get this yourself.

You would grab the current date and then do a datediff compared to Jan 1st, and that will give you the day of year (adding one to it to include Jan 1). From there you divide by 7 and format to have no decimal and you then have week of year (adding one to include week 1).

For example:

%%[

set @today = NOW()
set @year = DatePart(@today,'year')
set @startDate = FormatDate(Concat("01/01/",@year),"MM/DD/YYYY")

set @dayofYear = ADD(DateDiff(@startDate,@today,'D'),1)
set @weekofYear = ADD(FormatNumber(DIVIDE(@dayofYear,7),"N0"),1)
]%%

Today: %%=v(@today)=%%<br>
Year: %%=v(@year)=%%<br>
StartDate: %%=v(@startDate)=%%<br>
DayofYear: %%=v(@dayofYear)=%%<br>
WeekofYear: %%=v(@weekofYear)=%%

Outputs:

Today: 5/22/2019 1:24:46 PM
Year: 2019
StartDate: 01/01/2019
DayofYear: 142
WeekofYear: 21 
2
  • Aha! Great thought - just perform the math to find difference between today and Jan 1. Thanks for that answer! That should definitely work. Granted, dividing dayofyear/7 doesn't always give exactly the right answer (think if Jan 1 was on fri/sat/sun, that would be week 52/53 of previous year though I suppose could evaluate that too if we needed), but for this project, will absolutely cover the requirements. Thanks again! May 24 '19 at 13:30
  • 1
    yeah its not perfect, but with the +1 and rounding down will give the right WOY 99 out of 100 times May 24 '19 at 13:45

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.