VBScript: Add Leading Zero to Date Function Output
When you generate reports/files using VBScript periodically, it is always a good idea to suffix the file name with date/time components - e.g., "REPORT_20060811" - as it makes files easier to locate because they would already be sorted.
Using functions Year( Date ),
Month( Date ), Day( Date ), subcomponents can be extracted
to create filename suffix. You can also use DatePart( datetype,date )
function to extract the same components. But the problem with using any of these
functions as they are, is that you would not get proper sorting orders because
these will output single digits for numbers less than 10. For example, the
following two lines of code will generate date components which will not have
proper sorting order
strDate =
OR
strDate
= DatePart("yyyy",Date) _
& DatePart("m",Date) _
&
DatePart("d",Date)
To generate the string which will have the right sorting order, you need to
append leading zeros to entries less than 10. That is what the following line of
code does. It appends leading zero to all the entities, extracts 2 characters
from right, and builds the string.
strDate =
& Right("0" & DatePart("m",Date), 2) _
& Right("0" & DatePart("d",Date), 2)


21 Comments:
Elegant! Only other function I found to do the exact same thing was about 30 lines of code. Thanks.
Wow, this is awesomely simple and just what I needed in my script. Thanks!
Absolutely beautiful. I needed the same thing. Either the dates are wrong on the two comments above, or for some nutty reason the last two days have generated a number of people needing and appreciating your post over 2 years ago!
Thank you so much. I looked high and low for example code on how to save a date in reverse and this works perfect.
Thanks, I used this to get leading zeros in a timestamp as well:
strTime = Right("0" & Hour(Now), 2) & ":" & Right("0" & Minute(Now), 2) & ":" & Right("0" & Second(Now), 2)
This comment has been removed by the author.
I have to go back through years of code and remove my clunky AddLeadingZero() functions. Thanks for posting this!
!bravis! this is great
Amazingly simple yet perfect for what I need.
strDate = Format(Date, "yyyymmdd")
Will do the same. Looks shorter to me.
See also
http://msdn.microsoft.com/en-us/library/73ctwf33(VS.80).aspx
Format function doesn't work in VBScript, works only in Visual Basic.
http://www.4guysfromrolla.com/webtech/051601-1.shtml
Very handy! Thank you very much.
Thanks!!!
Cheers, Just wat was needed.
Wow, beautiful code, ver nice!
Excellent!
I just used this code snippet to cleanup a batch file that used dated file names. Very helpful and much cleaner.
~drofmij
Great! Thank you so much!
Just what I needed. Thanks!
Perfect! Just what I needed for my RoboCopy script.
very clever : )
Nicely done! I've been looking all over the place for a short elegant solution... this is the only one!
Thanks!
Post a Comment
Links to this post:
Create a Link
<< Home