创建从字符串DateTime对象 [英] Creating DateTime object from string
问题描述
我目前正在从文本文件中读取数据的分类,并分析了一切。一个被解析出来的物品是一个开始时间,格式的事件:
YYMMDDHHMM
1306050232
然后我分析出以下几点:
字符串一年=20+时间[0]的ToString()+时间[1]的ToString();
串月=时间[2]的ToString()+时间[3]的ToString();
串天=时间[4]的ToString()+时间[5]的ToString();
串小时=时间[6]的ToString()+时间[7]的ToString();
串分钟=时间[8]的ToString()+时间[9]的ToString();
串AMPM =;
INT hourInt = Convert.ToInt32(小时);
如果(hourInt< = 12)
{
时间=月+。 +日+。 +一年+@+小时+:+分++AM;
AMPM =AM;
}
,否则
{
hourInt = hourInt - 12;
时间=月+。 +日+。 +一年+@+ hourInt.ToString()+:+分++PM;
AMPM =PM;
}
一旦这些被解析出来,我结合的变量,并试图把它成日期时间。
字符串tempStartTime =年+ - +月+ - +日++小时+:+分钟++ AMPM;
字符串开始时间= DateTime.ParseExact(tempStartTime,YYYY-MM-DD HH:MM TT,NULL);
我的问题是,我得到这样的警告,从尝试捕捉:
System.FormatException:字符串未被识别为有效的DateTime。在System.DateTime.ParseExact(一个String,字符串格式,提供的IFormatProvider)
在Project.GUI.parseSchedule(的Int32数)
我不明白为什么,以及如何正确地做到这一点。
我要的是从文件采取的开始时间,将其转换为datetime对象,之后就可以进行操作。
< DIV CLASS =h2_lin>解决方案
为什么不直接跟你开始与格式解析?
VAR DT = DateTime.ParseExact(时间,YYMMDDHHMM,CultureInfo.InvariantCulture);
有没有必要让所有的预处理你正在做的。
$ B的$ bI currently am reading from a text file an assortment of data, and parsing out everything. One of the items being parsed out is a start time for an event in the format of:
yyMMddHHmm
1306050232
I then parse out to the following:
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";
}
once these are parsed out, i combined the variables, and try to put it into a DateTime.
string tempStartTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + " " + ampm;
string starttime = DateTime.ParseExact(tempStartTime, "yyyy-MM-dd HH:mm tt",null);
my issue is, I get a warning like this from the 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)
I don't understand why, or how to correctly do this.
All I want is to take the start time from the file, convert it to a datetime object, and operate on it afterwards.
Why not simply parse with the format you are starting with?
var dt = DateTime.ParseExact(time, "yyMMddHHmm", CultureInfo.InvariantCulture);
There's no need for all of the pre-processing you're doing.
这篇关于创建从字符串DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!