Formatting dates in VBScript

14. November 2009

As everyone knows, VBScript blows. However, on occassion, we sometimes are forced to work in it. One significant limitation is that VBScript does not provide a function to format dates with any arbitrary date format string. There are a number of solutions on the net but I have discovered one that provides significantly more power since it leverages the .NET Framework.

Public Function FormatDate( dDateValue, sFormat )
'PURPOSE: To format a date with any arbitrary format
'ARGS:
'   sFormat is the defined formats as used by the .NET Framework's System.DateTimeFormatInfo.
'       Note that this format is case-sensitive.
'CALLS:
'   1. System.Text.StringBuilder class in the .NET Framework.
'EXAMPLE CALL:  
'   Dim sFormatedDate
'   sFormatedDate = FormatDate( "1/1/1900 12:00 AM", "MM/dd/yy" )
'   Or
'   sFormatedDate = FormatDate( "1/1/1900 12:00 AM", "MM/dd/yyyy" )
'DESIGN NOTE:
'   This function leverages the fact that System.Text.StringBuilder is COMVisible.
'   Thus, we can call its AppendFormat function from here.
'   You can find more information about the format string parameters allowed at
'   http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx

    Dim oStringBuilder
    Dim sSbFormatString

    If Not IsDate( dDateValue ) Then
        FormatDate = vbNullString
        Exit Function
    End If    
    
    'if an empty format string is passed, then simply return
    'the value using the default shortdate format.
    If Len(sFormat & vbNullString) = 0 Then
        sSbFormatString = "{0:d}"
    Else
        sSbFormatString = "{0:" & sFormat & "}"
    End If
    
    sSbFormatString = "{0:" & sFormat & "}"
    Set oStringBuilder = CreateObject("System.Text.StringBuilder")
    FormatDate = oStringBuilder.AppendFormat(sSbFormatString, dDateValue)
    Set oStringBuilder = Nothing
End Function

 

.NET Development, Unintended Consequences

blog comments powered by Disqus