Rabia Khan
Rabia Khan

Reputation: 53

Format Date to mm/dd/yy

I am new t VBScript. I want to format my date from mm/dd/yyyy to mm/dd/yy. I used FormatDateTime(Date(),2) but it doesn't work for me. For Example:

if the date is July 1st, 2015, the above function outputs 7/1/2015 but i want it to be 07/01/15.

Any ideas how to do that? I have researched a lot but I couldn't figure it out.

Upvotes: 1

Views: 3867

Answers (2)

Martha
Martha

Reputation: 3854

You can write your own function to format the date exactly how you want.

Function MyDateFormat(TheDate)
    dim m, d, y
    If Not IsDate(TheDate) Then
        MyDateFormat = TheDate '- if input isn't a date, don't do anything
    Else
        m = Right(100 + Month(TheDate),2) '- pad month with a zero if needed
        d = Right(100 + Day(TheDate),2) '- ditto for the day
        y = Right(Year(TheDate),2)
        MyDateFormat = m & "/" & d & "/" & y
    End If
End Function

Note that the output of the above is a string, not a date, but the same goes for FormatDateTime.

Upvotes: 1

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Based on this answer (follow the 'Linked' links for background):

Option Explicit

Class cFormat
  Private m_oSB
  Private Sub Class_Initialize()
    Set m_oSB = CreateObject("System.Text.StringBuilder")
  End Sub ' Class_Initialize
  Public Function formatOne(sFmt, vElm)
    m_oSB.AppendFormat sFmt, vElm
    formatOne = m_oSB.ToString()
    m_oSB.Length = 0
  End Function ' formatOne
  Public Function formatArray(sFmt, aElms)
    m_oSB.AppendFormat_4 sFmt, (aElms)
    formatArray = m_oSB.ToString()
    m_oSB.Length = 0
  End Function ' formatArray
End Class ' cFormat

Dim oFmt : Set oFmt = New cFormat
WScript.Echo oFmt.FormatOne("Today: {0:MM\/dd\/yy}", #7/1/2015#)

output:

cscript 32272088.vbs
Today: 07/01/15

Upvotes: 1

Related Questions