问题
I use below program to change the date format based on the value setup in variable(cDataFormat). But the concern is this can be changed by the user and the program should act accordingly
DEFINE VARIABLE cDate AS DATE NO-UNDO.
DEFINE VARIABLE clogindate AS CHARACTER NO-UNDO.
DEFINE VARIABLE cDateformat AS CHARACTER NO-UNDO INIT "YYYY/MM/DD". /*this can be changed by
user*/
cDate = DATE(11/27/2020).
IF cDateformat = "YYYY/MM/DD" THEN clogindate = string(year(cDate),"9999") +
string(month(cDate),"99") + string(day(cDate),"99").
ELSE IF cDateformat = "YY/MM/DD" THEN clogindate = string(year(cDate),"99") +
string(month(cDate),"99") + string(day(cDate),"99").
ELSE IF cDateformat = "MM/DD/YY" THEN clogindate = string(month(cDate),"99") +
string(day(cDate),"99") + string(year(cDate),"9999").
/* AND SO ON...... as you know writing so much lines not the smartest way..Please give any idea*/
DISP clogindate.
回答1:
Instead of using IF THEN ELSE IF ELSE IF
, use the CASE
statement. Readability is better.
When you only have patterns MM
, DD
, YY
and YYYY
, you could use the REPLACE
statement to have less lines of code.
clogindate = cDateformat.
clogindate = REPLACE(clogindate, "YYYY", STRING(YEAR(cDate), "9999")).
clogindate = REPLACE(clogindate, "YY", STRING(YEAR(cDate), "99")).
clogindate = REPLACE(clogindate, "MM", STRING(MONTH(cDate), "99")).
clogindate = REPLACE(clogindate, "DD", STRING(DAY(cDate), "99")).
来源:https://stackoverflow.com/questions/65032245/how-to-change-date-format-based-on-variable-initial-value