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

How to parse an ISO 8601 Timestamp in vbScript

正常的ASP/VBScript 函数isDate 和CDate 不能处理ISO8601 格式的日期字符串。有像here.

这样的导出函数

如何将它们再次转换为日期时间值?

以防万一有人陷入同样的​​陷阱 (isDate('2010-08-12T00:00:00') = False),我想在这里展示我的解决方案。

您可以像 isDateCDate 一样使用 isIsoDateCIsoDate,下面的测试用例。

<% 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

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