Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add zero in front of single digit day in VB

Tags:

vb.net

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?

like image 924
Bladefreak Avatar asked Sep 11 '25 10:09

Bladefreak


2 Answers

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")
like image 131
Steven Doggart Avatar answered Sep 13 '25 20:09

Steven Doggart


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.

like image 29
programmergirl90 Avatar answered Sep 13 '25 20:09

programmergirl90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!