Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating DateTime object from string

Tags:

c#

datetime

I 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.

like image 282
PhoenixLament Avatar asked Jun 05 '13 01:06

PhoenixLament


1 Answers

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.

like image 182
Matt Johnson-Pint Avatar answered Sep 22 '22 00:09

Matt Johnson-Pint