VBScript: Adding Leading Zeros to a Date

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) 


Author: Rick Cable / AKA Cyber Abyss

A 16 year US Navy Veteran with 25+ years experience in various IT Roles in the US Navy, Startups and Healthcare. Founder of FinditClassifieds.com in 1997 to present and co-founder of Sports Card Collector Software startup, LK2 Software 1999-2002. For last 7 years working as a full-stack developer supporting multiple agile teams and products in a large healthcare organization. Part-time Cyber Researcher, Aspiring Hacker, Lock Picker and OSINT enthusiast.