c# - 从字符串创建 DateTime 对象

标签 c# datetime

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

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/

相关文章:

c# - 抓取和放下物体

javascript - 为什么在 JavaScript 中转换为日期对象时要从月份中减去 1?

linux - 如何转换dd/mm/yy hh :mm:ss to yyyy-mm-ddThh:mm:ss using linux?

python - 无法以足够的精度将 matlab datenum 格式转换为 python datetime

c# - 如何在 C# 字符串格式函数 Razor 中添加多个空格?

c# - 抑制ASPX文件的生成错误

c# - 如何在复合模型上应用 Required 属性?

c# - Windows 7 上的 SSL 客户端 SSPI 错误

python - 如何将以小时(h)为索引单位的pandas时间序列转换为pandas日期时间格式?

php - MSSQL Server INSERT NULL,但在 DATETIME 中插入 GetDate()