Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
如何使用 C# 将月份或日期转换为 2 位字符串
例如:(02 而不是 2)
如果您有DateTime,请使用其字符串格式化程序:
DateTime
string month = DateTime.Now.ToString("MM"); // or "dd" for day
或者,如果使用您拥有的数字更有意义,请使用数字格式化程序:
string monthStr = monthInt.ToString("00");
用于"MM"两位数月份和"dd"两位数日。
"MM"
"dd"
string month = DateTime.Now.ToString("MM");
请参阅:自定义日期和时间格式字符串 - MSDN
DateTime.Now.Day.ToString().PadLeft(2, '0');