如何使用 C# 将月或日转换为 2 位字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19233486/
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
How to make convert a Month or Day to reflect as a 2 digit string using C#
提问by Pinch
How does one convert a Month or Day to reflect as a 2 digit string using C#
如何使用 C# 将月或日转换为 2 位字符串
For example : (02 instead of 2)
例如:(02 而不是 2)
采纳答案by Tim S.
If you have a DateTime
, use its string formatters:
如果您有DateTime
,请使用其字符串格式化程序:
string month = DateTime.Now.ToString("MM"); // or "dd" for day
Or if it makes more sense to work with a number that you have, use the numeric formatters:
string monthStr = monthInt.ToString("00");
回答by Pinch
DateTime.Now.Day.ToString().PadLeft(2, '0');
回答by Habib
Use "MM"
for double digits month and "dd"
for double digits days.
使用"MM"
了两位数月和"dd"
为两位数天。
string month = DateTime.Now.ToString("MM");