gpinkas
gpinkas

Reputation: 2591

How to parse an ISO 8601 Timestamp in vbScript

The normal ASP/VBScript functions isDate and CDate can not handle ISO8601 formatted date strings. There are export functions like here.

How do you convert these into a datetime value again?

Upvotes: 4

Views: 2950

Answers (1)

gpinkas
gpinkas

Reputation: 2591

Just in case someone falls in the same trap (isDate('2010-08-12T00:00:00') = False), I want to present my solution here.

You can use isIsoDate and CIsoDate like isDate and CDate, test cases below.

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

Script Output:

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

Note: The conversion is quite basic, Time zone information is not taken into account.

Upvotes: 4

Related Questions