我目前正在从一个文本文件中读取各种数据,并解析所有内容。正在解析的项目之一是事件的开始时间,格式为:
yyMMddHHmm
1306050232
然后我解析出以下内容:
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";
}
一旦这些被解析出来,我就组合变量,并尝试将其放入 DateTime 中。
string tempStartTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + " " + ampm;
string starttime = DateTime.ParseExact(tempStartTime, "yyyy-MM-dd HH:mm tt",null);
我的问题是,我从 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)
我不明白为什么,或者如何正确地做到这一点。
我只想从文件中获取开始时间,将其转换为日期时间对象,然后对其进行操作。
最佳答案
为什么不简单地使用您开始使用的格式进行解析?
var dt = DateTime.ParseExact(time, "yyMMddHHmm", CultureInfo.InvariantCulture);
您不需要进行所有预处理。
关于c# - 从字符串创建 DateTime 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16930138/