I want to get a date in full format in my vbscript. For example, I put
DateParam = FormatDateTime(Date()-1, 2)
But it returns
3/8/201
The FormatDateTime function is useless, because it depends on the user specific and global Regional Settings.
The best (most gain for least effort) solution - tapping into .NET - is flawed for dates; again because of the dependency on the Regional Settings.
If you want/need to roll your own function, start with something like fmtDate().
Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder")
Function sprintf(sFmt, aData)
g_oSB.AppendFormat_4 sFmt, (aData)
sprintf = g_oSB.ToString()
g_oSB.Length = 0
End Function
Function fmtDate(dtX)
fmtDate = Join(Array( _
Right(100 + Month(dtX), 2) _
, Right(100 + Day(dtX), 2) _
, Year(dtX) _
), "/")
End Function
Dim dtYesterday : dtYesterday = Date() - 1
WScript.Echo "Yesterday:", dtYesterday, GetLocale()
WScript.Echo "sprintf (silly) =>", sprintf("{0:MM/dd/yyyy}", Array(dtYesterday))
WScript.Echo "sprintf (clumsy) =>", sprintf("{0:MM}/{0:dd}/{0:yyyy}", Array(dtYesterday))
WScript.Echo "fmtDate =>", fmtDate(dtYesterday)
output:
Yesterday: 08.03.2012 1033
sprintf (silly) => 03.08.2012
sprintf (clumsy) => 03/08/2012
fmtDate => 03/08/2012
On second thought:
Escaping the "/" helps to make sprintf() usable:
WScript.Echo "sprintf (silly me) =>", sprintf("{0:MM\/dd\/yyyy}", Array(dtYesterday))
output:
sprintf (silly me) => 03/08/2012
So don't bother with fmt* functions but use .NET formatting.
ThisDate = Date()
MyDate = Right("0" & CStr(Month(ThisDate)), 2) & "/" & _
Right("0" & CStr(Day(ThisDate)), 2) & "/" & CStr(Year(ThisDate))