如何在vbScript中解析ISO 8601时间戳

时间:2015-09-02 15:08:18

标签: vbscript asp-classic

正常的ASP / VBScript函数isDate和CDate无法处理ISO8601格式的日期字符串。有here等出口函数。

如何将这些转换为日期时间值?

1 个答案:

答案 0 :(得分:3)

万一有人陷入同一个陷阱(isDate('2010-08-12T00:00:00') = False),我想在这里提出我的解决方案。

您可以使用isIsoDateCIsoDate,例如isDateCDate,以下测试用例。

<% option explicit %>
<%
    ' ----------------------------------------------------------------------------------------
    function isIsoDate(s_input)
        dim obj_regex

        isIsoDate = false
        if len(s_input) > 9 then ' basic check before creating RegExp
            set obj_regex = new RegExp
            obj_regex.Pattern = "^\d{4}\-\d{2}\-\d{2}(T\d{2}:\d{2}:\d{2}(Z|\+\d{4}|\-\d{4})?)?$"
            if obj_regex.Test(s_input) then
                on error resume next
                isIsoDate = not IsEmpty(CIsoDate(s_input))
                on error goto 0
            end if
            set obj_regex = nothing
        end if
    end function

    ' ----------------------------------------------------------------------------------------
    function CIsoDate(s_input)
        CIsoDate = CDate(replace(Mid(s_input, 1, 19) , "T", " "))
    end function



    ' ----------------------------------------------------------------------------------------
    ' -- Testing
    ' ----------------------------------------------------------------------------------------
    sub writeCheck(s_input)
        dim is_iso_date

        is_iso_date = isIsoDate(s_input)
        Response.Write "TEST: " & s_input & " = " & is_iso_date & vbNewline
        if is_iso_date then
            Response.Write "+ CONVERT: " & formatDateTime(CIsoDate(s_input)) & vbNewline
        end if
        Response.Write vbNewline
    end sub


    Response.ContentType = "text/plain"
    writeCheck "1234"
    writeCheck "2010-03-12"
    writeCheck "2010-03-12T12:34:56"
    writeCheck "2008-05-11T15:30:00Z"
    writeCheck "2010-99-12"
    writeCheck "2010-01-12T25:25:25"
%>

脚本输出:

TEST: 1234 = False

TEST: 2010-03-12 = True
+ CONVERT: 12.03.2010

TEST: 2010-03-12T12:34:56 = True
+ CONVERT: 12.03.2010 12:34:56

TEST: 2008-05-11T15:30:00Z = True
+ CONVERT: 11.05.2008 15:30:00

TEST: 2010-99-12 = False

TEST: 2010-01-12T25:25:25 = False

注意:转换非常基本,不考虑时区信息。