I have the following codes in visual basic that display the day/month/year
CStr(vDay) & "/" & (vMonth) & "/" & (vYear) & " " & (vHour) & ":" & (vMinute) & ":" & (vSecond), DateTime.Now
How can I add a "0" in front of a single digit day and month?
If your variables are integers, you can use the "D" format specifier to set how many digits you want, for instance:
vMonth.ToString("D2")
However, if you already have the value in a Date
object, then you can just use it's built-in formatting, which would be easier:
DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")
To account for all situations, PadLeft is most helpful. The first part is set total width for the integer, the second part is the character to be placed there.
vMonth.ToString().PadLeft(2, "0"c)
This would place a zero in front of single digit months.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With