C#substring缺少第一个零值

Mel*_*ier 0 c# substring

我有一个字符串日期,我想分成整数:年,月和日.例如,20160622应该返回year = 2016,month = 06和day = 22.这是代码:

        String dateString = "20160622";
        int year = Int32.Parse(dateString.Substring(0, 4));
        Console.WriteLine("year is " +year);
        Console.ReadKey();

        int month = Int32.Parse(dateString.Substring(4, 2));
        Console.WriteLine("month is " + month);
        Console.ReadKey();

        int jour = Int32.Parse(dateString.Substring(6, 2));
        Console.WriteLine("day is  " + jour);
        Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

当子串的第一个字符为'0'时,它不会作为子字符串的一部分返回.我得到以下输出:

year is 2016
month is 6
day is 22
Run Code Online (Sandbox Code Playgroud)

但我想得到

year is 2016
month is 06
day is 22
Run Code Online (Sandbox Code Playgroud)

Nat*_*ini 5

使用后Int32.Parse,该值为整数,整数不具有前导数字."06"变得只有6.

如果要使用前导数字打印值,则可以在将整数写入字符串时提供自定义格式:

Console.WriteLine("month is " + month.ToString("00"));
Run Code Online (Sandbox Code Playgroud)

ToString("00") 告诉C#将int转换回字符串,但将其渲染为两位数(如果需要,前导0).

这是一个尝试它的小提琴:小提琴