c# - 从字面上打印带有前导 0 的整数

标签 c# c#-4.0

我正在尝试打印像 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 日)

参见 DateTime.ToString Method (String) [MSDN]供引用。

关于c# - 从字面上打印带有前导 0 的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8293287/

相关文章:

file - 将大数据写入文件缓存问题

html - 如何在经典的 ASP Web 应用程序之上集成 WebSockets?

c# - 从具有整数属性的 List<T> 返回 List<int>?

c# - 删除 xmlns :i ="http://www.w3.org/2001/XMLSchema-instance" when using DataContractSerializer

c# - List 对象的 !Contains() 不起作用

c# - 如何在 .NET Remoting 中远程处理事件?

C# 顶点边

c# - 使用正则表达式拆分字符串

c# - 何时检查 InnerException

c# - 如何确定非空对象是否为可空结构?