我正在尝试打印像 0101.... 1231 这样的数字,其中前两位数字是月份,接下来的两位数字是天数。我这样做了:
int d, m;
for (m = 01; m <= 12; m++)
for (d = 01; d <= 31; d++)
Console.WriteLine(loc + m.ToString() + d.ToString());
// Directory.CreateDirectory(loc + m.ToString() + d.ToString());
这是打印数字 11 而不是 0101。如何将整数 1 到 9 打印为 01-09?
最佳答案
Console.WriteLine(loc + m.ToString("D2") + d.ToString("D2"));
参见 Standard Numeric Format Strings [MSDN]供引用。
虽然:
var date = new DateTime(2011, 1, 1);
while (date < new DateTime(2012, 1, 1))
{
Console.WriteLine(loc + date.ToString("MMdd"));
// ^ MMdd stands for Month-Month, day-day (indicating you want them both displayed in a double digit format)
// (uppercase M is used because lowercase m is already taken, it stands for minutes)
date = date.AddDays(1);
}
将使您更方便地控制输出日期格式,并帮助您避免打印出不存在的日期(例如 4 月 31 日或 2 月 30 日)
关于c# - 从字面上打印带有前导 0 的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8293287/