Visual FoxPro 字符串到日期的转换

Visual FoxPro String to Date Conversion

如何将字符串 30-Jul-17 转换为日期格式 07/30/17

我不相信 VFP 中有内置的方法来解析缩写的月份字符串(甚至完整的月份名称)。如果是我,我会像这样为每个缩写月份使用 CASE 语句。

lcStringDate = "30-Jul-17"
lcDay = LEFT(lcStringDate, 2)
lcMonth = SUBSTR(lcStringDate, 4, 3)
lcYear = "20"+RIGHT(lcStringDate, 2)

*!* Here you'd need to have code to convert abbreviated
*!* month to a numeric month
DO CASE
    CASE lcMonth = "Jan"
        lcNumericMonth = "1"
    CASE lcMonth = "Feb"
        lcNumericMonth = "2"
    .
    .
    .
ENDCASE

?CTOD(lcNumericMonth+"/"+lcDay+"/"+lcYear)
*!* this would output "07/30/17" if SET CENTURY is OFF
*!* this would output "07/30/2017" if SET CENTURY is ON

要稍微扩展 Steve 提供的内容,您可以将其作为一个函数并重复调用...

    lcDate = "30-Jul-17"
    ? DMYToDate( lcDate )

    lcDate = "15-August-17"
    ? DMYToDate( lcDate )

    lcDate = "29-Feb-17"    && No such feb 29, 2017
    ? DMYToDate( lcDate )

    lcDate = "32-Mar-17"    && no month 32 days
    ? DMYToDate( lcDate )


FUNCTION DMYToDate
LPARAMETERS lcTryDate
    local lnDay, lnYear, lcMonth, tmpDate, ldNewDate
    lnDay = INT( VAL( LEFT( lcTryDate, 2 )))
    lnYear = 2000 + INT(VAL(RIGHT( lcTryDate, 2 )))
    lcMonth = SUBSTR( lcTryDate, 4, 3 )

    */ Cycle through each month with arbitrary start date...
    tmpDate = DATE(2000,1,1)
    DO WHILE YEAR( tmpDate ) < 2001
        IF ATC( lcMonth, CMONTH( tmpDate ) ) = 1
            EXIT
        ENDIF 
        tmpDate = GOMONTH( tmpDate, 1 )
    ENDDO 
    IF YEAR( tmpDate ) > 2000
        */ No such month found, return empty date.
        RETURN CTOD( ""  )
    ENDIF 

    TRY
        ldNewDate = DATE( lnYear, MONTH( tmpDate ), lnDay )
    CATCH 
        ldNewDate = CTOD( "" )
    ENDTRY 

    RETURN ldNewDate
ENDFUNC

试试这个:

"a" 是你的日期字符串

DATE(2000+VAL(SUBSTR(a,8,2)),int((AT(SUBSTR(UPPER(a),4,3),"JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC")-1)/3)+1,VAL(SUBSTR(a,1,2)))