Obtaining DayOfWeek and WeekOfYear in RPG IV

Article ID: 15778

The code below shows how to compute the day of the week and the week of the year using date-related BIFs that have been available in RPG IV since V5R1.

H NoMain

 * ------------------------------------------------------- Prototypes
D DayOfWeek       PR             5I 0
D                                 D   Value

D WeekOfYear      PR             5I 0
D                                 D   Value

 * -----------------------------------------------------------------
 *
 * Procedure: DayOfWeek
 * Description: Retrieve day of week using ISO 8601 standard
 *              (0=Monday - 6=Sunday)
 *
P DayOfWeek       B                   Export

D DayOfWeek       PI             5I 0
D  DateIn                         D   Value

D NbrDays         S             10I 0

D Monday          C                   D('2001-01-04')

 /Free

  NbrDays = %DIFF(DateIn:Monday:*DAYS);
  Return  = %REM( %REM(NbrDays:7) + 7 : 7);

 /End-Free

P DayOfWeek       E

 * -----------------------------------------------------------------
 *
 * Procedure: WeekOfYear
 * Description: Retrieve week of year using ISO 8601 standard
 *              (Year starts on Monday of week containing January 4)
 *

P WeekOfYear      B                   Export

D WeekOfYear      PI             5I 0
D  DateIn                         D   Value

D                 DS
D Jan04Date                       D   INZ(D'0001-01-04')
D  Jan04Year                     4  0 Overlay(Jan04)

D FirstMonday     S               D
D Jan04DOW        S              5I 0

 /Free

  // Change Jan04Date to target year,
  // then calculate first Monday of target year
  Jan04Year   = %SUBDT(DateIn:*Y);           
  Jan04DOW    = DayOfWeek(Jan04Date);        
  FirstMonday = Jan04Date - %DAYS(Jan04DOW); 

  // If target date is before first Monday, switch to prior year
  If DateIn < FirstMonday;                   
    Jan04Year   = Jan04Year D 1;             
    Jan04DOW    = DayOfWeek(Jan04Date);      
    FirstMonday = Jan04Date - %DAYS(Jan04DOW);
  Endif;

  // Return week number (number of full weeks since first Monday + 1)
  Return %DIV(%DIFF(DateIn:FirstMonday:*DAYS):7) + 1;

 /End-Free

P WeekOfYear      E

The above code appeared in Bryan Meyers' iSeries NEWS article "RPG IV Turns V," which iSeries Network professional members can read at http://www.iseriesnetwork.com/Article.cfm?ID=10955.

ProVIP Sponsors

ProVIP Sponsors