Monday, September 26, 2011

COBOL: Subtract given number of months from a date

The below code snippet can subtract any given number of months from a date.

01 MONTH-END-DD PIC X(24) VALUE '312831303130313130313031'.
01 TBL-MONTH-END REDEFINES MONTH-END-DD.
   03 TBL-MONTH-END-DAY OCCURS 12 TIMES.
      05 TBL-MONTH-END-DD PIC 9(02).

01 WS-DATE.
   02 YYYY PIC 9(4).
   02 MM PIC 99.
   02 DD PIC 99.

MOVE INPUT-DATE TO WS-DATE

DIVIDE WS-NO-OF-MONTHS BY 12 GIVING WS-NO-OF-YEARS
       REMAINDER WS-REMAINING-MONTHS

SUBTRACT WS-NO-OF-YEARS FROM YYYY

IF MM > WS-REMAINING-MONTHS
   COMPUTE MM = MM - WS-REMAINING-MONTHS
ELSE
   SUBTRACT 1 FROM YYYY
   COMPUTE MM = 12 - WS-REMAINING-MONTHS
END-IF

IF ( FUNCTION MOD (YYYY, 400) = 0) OR
   ( FUNCTION MOD (YYYY, 4) = 0 AND
     FUNCTION MOD (YYYY, 100) NOT = 0 )
     MOVE '29' TO TBL-MONTH-END-DD (3:2)
ELSE
     MOVE '28' TO TBL-MONTH-END-DD (3:2)
END-IF

IF DD > TBL-MONTH-END-DAY (MM)
   MOVE TBL-MONTH-END-DAY (MM) TO DD
END-IF

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.