Search code examples
abapfunction-module

FM to convert time from 24hr to 12hr format?


I have to format a DateTime which is in UTC based on user settings which include its time zone (CET/IST etc) and time format (24hr/12hr).

I could find CONVERT TIME STAMP statement which takes only TIME ZONE as a parameter and does that conversion:

DATA: lv_timestampl TYPE timestampl VALUE '20200219095959.0000000',
      lv_date       TYPE d,
      lv_time       TYPE t.
CONVERT TIME STAMP lv_timestampl TIME ZONE sy-zonlo INTO DATE lv_date TIME lv_time.

My objective is to convert this lv_timestampl based on TimeZone and TimeFormat together.

PS: I could just do that -12 manipulation on lv_time after CONVERT TIME STAMP statement and append PM/AM but I am looking for a standard way of doing it.


Solution

  • OK, let me be your living help today, if you were not able to find string templates help.

    Template to convert timestamp to UTC:

    DATA(ld_tims_utc) = |{ lv_timestampl TIMESTAMP = ENVIRONMENT }|.
    

    returns

    19.02.2020 09:59:59,0000000

    Template to convert timestamp to explicitly specified timezone:

    DATA(ld_tims_zone) = |{ lv_timestampl TIMESTAMP = ENVIRONMENT TIMEZONE = 'CET' }|.
    

    returns

    19.02.2020 10:59:59,0000000

    Getting time and date from timestamp (not timestampl, so conversion needed):

    cl_abap_tstmp=>systemtstmp_utc2syst( EXPORTING
                                           utc_tstmp = CONV timestamp( lv_timestampl )
                                         IMPORTING
                                           syst_date = lv_date
                                           syst_time = lv_time ).
    

    Output in 12h format:

    SET COUNTRY 'US'.
    DATA(time_us) = |{ lv_time TIME = ENVIRONMENT }|. "gives 01:55:43 PM
    

    Output in 24h format:

    SET COUNTRY 'DE'.
    DATA(time_de) = |{ lv_time TIME = ENVIRONMENT }|. "gives 13:55:43
    

    For the output of AM/PM time formats, they need to be maintained in field TIMEFM of table USR01 aka User settings or table t005x aka Country settings (tcode OY01).