String.Substring古怪

flo*_*dob -2 c# string substring

好的,我已经醒了太久了.生气.请有人告诉我为什么这不起作用.传入的字符串如"201212120600" Substring(0,4)返回"201"而不是"2012".我的大脑在融化.

    private DateTime StringToDateTimeUTC(String s)
    {
        System.Diagnostics.Debug.WriteLine(s);
        String syear = s.Substring(0, 4);
        System.Diagnostics.Debug.WriteLine(syear);

        int year = int.Parse(s.Substring(0, 4));
        int month = int.Parse(s.Substring(4, 2));
        int day = int.Parse(s.Substring(6, 2));
        int hour = int.Parse(s.Substring(8, 2));
        int minute = int.Parse(s.Substring(10, 2));
        DateTime dt = new DateTime(year, month, day, hour, minute, 0, DateTimeKind.Utc);
        return dt;
    }
Run Code Online (Sandbox Code Playgroud)

输出是:

201212120600

201

Guf*_*ffa 8

我认为你的字符串中确实有一个空格:

string s = " 201212120600";

Console.WriteLine(s);
String syear = s.Substring(0, 4);
Console.WriteLine(syear);

int year = int.Parse(s.Substring(0, 4));
Console.WriteLine(year);
Run Code Online (Sandbox Code Playgroud)

输出:

 201212120600
 201
201
Run Code Online (Sandbox Code Playgroud)


Jar*_*ger 5

当我将此代码粘贴到VS并运行它时,我得到了预期的输出:

201212120600
2012
Run Code Online (Sandbox Code Playgroud)

请注意,使用以下命令可以更轻松地实现此目标DateTime.ParseExact():

// using System.Globalization;
DateTime dt = DateTime.ParseExact(
    s,
    "yyyyMMddHHmm",
    CultureInfo.CurrentCulture.DateTimeFormat,
    DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Run Code Online (Sandbox Code Playgroud)

......会让dt你回归的东西也一样.