如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:28:42  来源:igfitidea点击:

How to make convert a Month or Day to reflect as a 2 digit string using C#

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");

See: Custom Date and Time Format Strings - MSDN

请参阅:自定义日期和时间格式字符串 - MSDN