vb.net VB中个位数日前加零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13786304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:30:33  来源:igfitidea点击:

Add zero in front of single digit day in VB

vb.net

提问by Bladefreak

I have the following codes in visual basic that display the day/month/year

我在visual basic中有以下代码显示日/月/年

CStr(vDay) & "/" & (vMonth) & "/" & (vYear) & " " & (vHour) & ":" & (vMinute) & ":" &     (vSecond), DateTime.Now

How can I add a "0" in front of a single digit day and month?

如何在一位数的日期和月份前添加“0”?

回答by Steven Doggart

If your variables are integers, you can use the "D" format specifier to set how many digits you want, for instance:

如果您的变量是整数,您可以使用“D”格式说明符来设置您想要的位数,例如:

vMonth.ToString("D2")

However, if you already have the value in a Dateobject, then you can just use it's built-in formatting, which would be easier:

但是,如果您已经在Date对象中拥有值,那么您可以使用它的内置格式,这会更容易:

DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")

回答by programmergirl90

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.

考虑到所有情况,PadLeft 最有帮助。第一部分设置整数的总宽度,第二部分是要放置在那里的字符。

vMonth.ToString().PadLeft(2, "0"c)

This would place a zero in front of single digit months.

这将在个位数月份前放置一个零。