sapdev logo background
sapdev logo sapdev logo
Comments

Add n number of working days to date




The following ABAP code adds/Subtracts n number of months from a particular date. You would think this should be a relativly straight forward process by using the SAP 'CALCULATE_DATE' function module. Unfotunately this does not take into account months having a different number of days i.e. If you start at 31.05.2003 and subtract 1 month the result would be 31.04.2003 which is an invalid date as April only has 30 days. This causes the SAP FM to return the date as 00000000. The code below provides a solution to this issue.

Update: If it exists on your system a much simplier way would be to use function module MONTH_PLUS_DETERMINE as this takes into account months with different amounts of days.

Simply add the below ABAP FORM into you report code and call it using the usual PERFORM command:

DATA: ld_date TYPE sy-datum. ld_date = sy-datum. PERFORM calculate_date using '-4' changing ld_date.


*&-----------------------------------------------------*
*&      Form  CALCULATE_DATE
*&-----------------------------------------------------*
*       Add/Subtract n number of months from a date
*------------------------------------------------------*
*  -->  p_months  Number of months to add/subtract
*  <--  p_date    Start date and result date
*------------------------------------------------------*

FORM calculate_date USING p_months
                    CHANGING p_date.

  DATA: ld_datestor TYPE sy-datum.

  ld_datestor = p_date.
  CALL FUNCTION 'CALCULATE_DATE'
       EXPORTING
            months      = p_months
            start_date  = p_date
       IMPORTING
            result_date = p_date.

* Check resultant date is valid.
  IF p_date IS INITIAL.
*  Resultant day must have been beyond last day of month, Repeat
*  process but change date to first day of month
    p_date = ld_datestor.
    p_date+6(2) = '01'.
    CALL FUNCTION 'CALCULATE_DATE'
         EXPORTING
              months      = p_months
              start_date  = p_date
         IMPORTING
              result_date = p_date.

*   Now Find last day of resultant month (First day of next month - 1)
*   ******************************************************************
*   Add 1 to month
    CALL FUNCTION 'CALCULATE_DATE'
         EXPORTING
              months      = '01'
              start_date  = p_date
         IMPORTING
              result_date = p_date.

*   Subtract 1 from day
    CALL FUNCTION 'CALCULATE_DATE'
         EXPORTING
              days        = '-1'
              start_date  = p_date
         IMPORTING
              result_date = p_date.
  ENDIF.

ENDFORM.                    " CALCULATE_DATE




comments powered by Disqus