How to change date format based on variable initial value?

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 17:20:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!