Search code examples
xmlvbscripthp-uft

Comparing DateFormat with Date String


I have a Date = "20180719" which I am taking out from XML file. I have a drop down field 'Manufacturing Date'(Windows application) which has format "YYYYMMDD".

Now I have to validate whether the 'Date' is in the correct Date Format as provided in 'Manufacturing Date'.

Is there any function in which I can convert Date into DateFormat ?

Thanks !


Solution

  • An XML file should have a schema for validation, so that badly formatted dates (strings!) could be caught. If your XML can contain surprises, you have to check the plausibility of the year/month/day-parts. In code:

    Dim aT : aT = Split("20180719 19072018 07192018 20181212 20181313 11112233 33331122")
    Dim sD
    For Each sD in aT
        WScript.Echo sD, verdict(sD)
    Next
    
    ' "YYYYMMDD" format hard coded, using DateSerial to check the plausibility of the y-m-d-parts
    Function verdict(sD)
      verdict = "invalid"
      If 8 = Len(sD) Then
         Dim nY : nY = CInt(Left(sD, 4))
         Dim nM : nM = CInt(Mid(sD, 5, 2))
         Dim nD : nD = CInt(Right(sD, 2))
         Dim dD : dD = DateSerial(nY, nM, nD)
         If sD = Year(dD) & Right(100 + Month(dD), 2) & Right( 100 + Day(dD), 2) Then verdict = "ok"
      End If
    End Function
    

    output:

    cscript 51613138.vbs
    20180719 ok
    19072018 invalid
    07192018 invalid
    20181212 ok
    20181313 invalid
    11112233 invalid
    33331122 ok
    

    In addition, you may range check the year (using the numerical nY variable). Some border cases (Did the author of "20180102" want to specify a day in januar or february?) can't be decided, however.