Homelab, Linux, JS & ABAP (~˘▾˘)~
 

[ABAP] Get the last day of the previous month

I recently had to find the last day of the previous month. I found the Method get_last_day_prev_month of class cl_bs_period_toolset_basics doing the job. The actual logic is super simple:

  rv_date      = iv_date.
  rv_date+6(2) = '01'.
  rv_date      = rv_date - 1.

That’s why I thought about whether I needed a separate method at all, or whether I could do it directly in a one-liner. My first idea was to use the LET operator in combination with CONV (Option 2). This works, but does not look very intuitive, and I noticed it can be done even simpler without using LET (Option 3). And if you already have a typed variable, you can do it even shorter with a single CONV (Option 4).

* Option 1
DATA(date_1) = cl_bs_period_toolset_basics=>get_last_day_prev_month( sy-datum ).

*Option 2
DATA(date_2) = CONV d( LET x = CONV d( sy-datum(6) && '01' ) IN x - 1 ).

*Option 3
DATA(date_3) = CONV d( CONV d( sy-datum(6) && '01' ) - 1 ).

* Option 4
DATA date_4 TYPE datum.
date_4 = CONV d( sy-datum(6) && '01' ) - 1.

cl_demo_output=>write_data( date_1 ).
cl_demo_output=>write_data( date_2 ).
cl_demo_output=>write_data( date_3 ).
cl_demo_output=>write_data( date_4 ).
cl_demo_output=>display( ).

All in all, I have to say that using the get_last_day_prev_month method is still the best solution as it is much more readable.