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) 


How to Concatenate a String using VBScript

How to Concatenate a String Value in VBScript

To concatenate string values using VBScript we use the ampersand (&) character to piece together our composite string value.

Code Example:

Srting1 = "Word 1"
String2 = "Word 2"
String3 = String1 & String2
or 
String3 = "Word 1" & "Word 2"
msgbox(String3)

The output value would be “Word 1 Word 2”.

If you’re more familiar with JavaScript, you might be used to concatenating strings using the plus character (+).

In VBScript you can only use the + operator on numeric values.