If this is VBScript then just break it up and pad it.
Dim LabelDate, FormattedDate
LabelDate = #2/7/2016#
FormattedDate = Right("00" & DatePart("d", LabelDate), 2) & "-" & _
Right("00" & DatePart("m", LabelDate), 2) & "-" & _
DatePart("yyyy", LabelDate)
'Test conversion
Call MsgBox(LabelDate & " to " & FormattedDate)
If you really want to break it down, you can do;
Dim LabelDate, FormattedDate
Dim LabelMonth, LabelMonth, LabelYear
LabelDate = #2/7/2016#
LabelYear = DatePart("yyyy", LabelDate)
LabelMonth = Right("00" & DatePart("m", LabelDate), 2)
LabelDay = Right("00" & DatePart("d", LabelDate), 2)
'Restructure them how you want...
FormattedDate = LabelDay & "-" & LabelMonth & "-" LabelYear
'Test conversion
Call MsgBox(LabelDate & " to " & FormattedDate)
Yet another approach to make the restructure a bit nicer is to use an Array()
.
Dim LabelDate, FormattedDate
Dim LabelDateArray
LabelDate = #2/7/2016#
LabelDateArray = Array( _
Right("00" & DatePart("d", LabelDate), 2), _
Right("00" & DatePart("m", LabelDate), 2), _
DatePart("yyyy", LabelDate) _
)
'Restructure using the Array...
FormattedDate = Join(LabelDateArray, "-")
'Test conversion
Call MsgBox(LabelDate & " to " & FormattedDate)
Just to explain what's going on
In the end you are wanting to take a date literal and format it for display purposes. Padding is actually simpler then it first appears, all you need to do is pre-append "00"
to the front of the value then append the specific DatePart()
(only needed for Month
and Day
). Then you use a simple hack to get the desired result using the Right()
function we take 2 characters from the left, which if you value is 1 character applies the "0"
padding.
Apparently it takes another answer to point out this out
Hardly relevant but as this answer highlights, you can also use
Month(LabelDate)
instead of DatePart("m", LabelDate)
Day(LabelDate)
instead of DatePart("d", LabelDate)
Both functions do the same thing and I don't know of any overriding reason to use one or the other, except maybe Month(LabelDate)
is shorter to write then DatePart("d", LabelDate)
. The above method will work using either so it's negligible.
Why do some examples use Right("0" &
not Right("00" &
instead?
It's simple, they are assuming you will always have a value for the Month
and Day
but as I have had in the past you won't always pass those values in from system functions, so for the occasions where a null
value is passed it will ensure that the date part is set to 00
.
Also it worth pointing out that what all these solutions produce is a string it's no longer a date so if you are going to perform date functions against it make sure, you either store the original value and use that or use CDate()
to convert the value to a valid date literal.
Useful Links