从字符串创建DateTime对象

Pho*_*ent 6 c# datetime

我目前正在从文本文件中读取各种数据,并解析所有内容.其中一个被解析的项目是事件的开始时间,格式为:

yyMMddHHmm
1306050232 
Run Code Online (Sandbox Code Playgroud)

然后我解析出以下内容:

string year = "20" + time[0].ToString() + time[1].ToString();
string month = time[2].ToString() + time[3].ToString();
string day = time[4].ToString() + time[5].ToString();
string hour = time[6].ToString() + time[7].ToString();
string minute = time[8].ToString() + time[9].ToString();
string ampm ="";
int hourInt = Convert.ToInt32(hour);

if (hourInt <= 12)
{
    time = month + "." + day + "." + year + "@" + hour + ":" + minute + " " + "AM";
    ampm= "AM";                         
}
else
{
    hourInt = hourInt - 12;      
    time = month + "." + day + "." + year + "@" + hourInt.ToString() + ":" + minute + " " + "PM";
    ampm= "PM";  
}
Run Code Online (Sandbox Code Playgroud)

一旦这些被解析出来,我就组合了变量,并尝试将它放入DateTime中.

string tempStartTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + " " + ampm;

string starttime = DateTime.ParseExact(tempStartTime, "yyyy-MM-dd HH:mm tt",null);
Run Code Online (Sandbox Code Playgroud)

我的问题是,我从try catch中收到这样的警告:

System.FormatException: String was not recognized as a valid DateTime.
   at System.DateTime.ParseExact(String s, String format, IFormatProvider provider)
   at Project.GUI.parseSchedule(Int32 count) 
Run Code Online (Sandbox Code Playgroud)

我不明白为什么,或者如何正确地做到这一点.

我想要的是从文件中获取开始时间,将其转换为日期时间对象,然后对其进行操作.

Mat*_*int 13

为什么不简单地用你开始的格式进行解析?

var dt = DateTime.ParseExact(time, "yyMMddHHmm", CultureInfo.InvariantCulture);
Run Code Online (Sandbox Code Playgroud)

您无需进行所有预处理.