I was recently developing a script to loop through an excel file and write the contents in to a text file. One of the specifications was that the output dates had to have leading zeros like 01/01/2021 but the excel file had them as 1/1/2021.
I thought there must a VBScript function like the built in CDate for or FormatDateTime but neither of these seemed to return dates with leading zeros so I wrote my own function to do it.
As in all programing, there are many ways to write this to get the same output but this way worked for me on the project I used it for.
VBScript FixDate Function to fix leading zeros in a date value
Function FixDate(strDate)
Dim iTemp, arrDate, item, strTemp
' my custom date fix function
' split the date in to an array by the "/" character
' check each date item and check to see if it is less than 1000
arrDate = Split(strDate,"/")
for each item in arrDate
if len(item) < 2 then
item = "0" & item
end if
' Next section makes sure there is no / at the end of the rebuilt date when I put it back together.
if item < 100 then
strTemp = strTemp & item & "/"
else
strTemp = strTemp & item
end if
Next
' Put the date back together
FixDate = strTemp
End Function
How to call this function
FixDate("1/1/2011")
or
FixDate(YourStringDate)