HP OpenVMS Systems

ask the wizard
Content starts here

Calculating Week Number?

» close window

The Question is:

How can I generate a weeknumber?
Is this by using the lexical function f$time or f$cvtime?

The Answer is :

  By week number, the OpenVMS Wizard will assume you mean the week within
  the year, and specifically a value between 1 and 52 inclusive.  As there
  are various accepted definitions for a week number, there is no single
  DCL lexical function or argument that can retrieve the desired.
  Given that there are only 52 weeks in a year, and given that DCL is not
  particularly suited for date arithmetic, and given that computers are
  fast, the simplest way to is to count the week.
  For example, assuming that week 1 starts on 1-Jan and week 2 starts on
  8-Jan (etc...), this procedure uses combination times to count backwards
  in multiples of 7 to find the first day not in the current year, at the
  same time as counting up weeks.
    $ day=F$CVTIME(p1,"ABSOLUTE","DATE")
    $ weeknum=0
    $ offset=0
    $ year=F$CVTIME(day,,"YEAR")
    $ loop:
    $   weeknum=weeknum+1
    $   offset=offset+7
    $   IF F$CVTIME("''day'-''offset'-0",,"YEAR").EQS.Year THEN GOTO loop
    $ WRITE SYS$OUTPUT weeknum
    $ EXIT
  Minor variations can be made to this procedure to accomodate other
  definitions for week number.
  Remember that in the worst case, the above procedure will loop for 53
  iterations, so unless your code is highly performance sensitive, it
  shouldn't be a problem. If your code is performance sensitive, please
  create and code an algorthm using a compiled language.
  Within a compiled language, you can generate the weeknumber for any
  given date.  For example, you can generate the week number for any
  given date using the strftime() C Run-time library function, and
  specifically the %W directive.  This will give you a week number in
  the range [00,53], where Monday is the first day of the week.  For
  the purposes of this C example, all days in the year preceding the
  first Monday are considered to be in week 0.
    For example, for current date:
    $ run x
    $ Monday May 06 2002 is in week number 18
    #include <time.h>
    #include <stdio.h>
    main() {
      char s[80];
      time_t t = time(NULL);
      struct tm *tms = localtime(&t);
      strftime(s, sizeof(s), "%A %B %d %Y is in week number %W", tms);

answer written or last revised on ( 10-JUN-2002 )

» close window