MainframeSupports
tip week 47/2012:

Recently I needed to find out which weeknumber a date belonged to. Instantly I thought that there must be a function in REXX to do this. But REXX disappointed me this time. REXX has a lot of builtin functions, but weeknumbers are not supported yet.

So for once I had to build the function myself. First of all I had to figure out how a weeknumber is actually defined and here I am talking about weeknumbers where the week starts on a monday. One of the definitions (there are several) is that the first week in a new year containing a thursday is week number one. So all you have to do is to count thursdays. Here is what I ended up coding:

/* REXX */
ARG DB2DATE
thisdate = TRANSLATE('abcdefgh', db2date, 'abcd-ef-gh')
say 'this week='week(thisdate)
exit
week:
  arg thisdate
  thisdays = date('D', thisdate, 'S') - 1
  year = substr(thisdate,1,4) + 0
  frstweekday = date('B', year'0101', 'S')//7
  weekno = (thisdays + frstweekday)%7 + (frstweekday < 4)
  if weekno = 0
  then
    weekno = week(year-1'1231')
return weekno

The important part is of course the function week. To demonstrate the function I have embedded it in a REXX program that accepts a date in DB2 format (YYYY-MM-DD) as input. I reformat this date into the format YYYYMMDD using translate to make it easier for REXX to handle. The week function accepts a date in format YYYYMMDD as input.

The exciting stuff is of course a first week without a thursday (MMDD=0101 is a friday, saturday or sunday). In this case I need to find out what the last weeknumber of the previous year is. The easy way to calculate this is to invoke the week function recursively (I love recursive solutions) using the last date of the previous year.

If you wonder about "+ (frstweekday < 4)" then remember that a condition in REXX always returns 1 when true and 0 when false. All I do is to add 0 or 1 to the number of calculated thursdays not in the first week. Another trick is to add 0 to the result of a substr. This makes it possible to make calculations on the result later in the recursive call to week. In other words if you know that a string variable contains a numeric value you can convert it into a real numeric value by adding 0 to it.

Previous tip in english        Forrige danske tip        Tip list