Reputation: 155
In a part of my system, I have this situation: I will receive a string that represents a date and another string that represents a time. I need to let these informations in DateTime. So, a made it:
string date = "17012012";
string hour = "103445";
date = string.Format("{0}/{1}/{2}", date.Substring(0, 2),
date.Substring(2, 2), date.Substring(4, 4));
hour = string.Format("{0}:{1}:{2}", hour.Substring(0, 2),
hour.Substring(2, 2), hour.Substring(4, 2));
DateTime example = new DateTime();
example = DateTime.Parse(string.Format("{0} {1}", date, hour));
Ok, but is it a good pattern? Are there a "more beautiful" way to do this?
Upvotes: 1
Views: 3001
Reputation: 317
One way or another your program must parse this format. I would have done like this:
string date = "17012012";
string time = "103445";
int year = Convert.ToInt32(date.Substring(4, 4));
int month = Convert.ToInt32(date.Substring(2, 2));
int day = Convert.ToInt32(date.Substring(0, 2));
int hour = Convert.ToInt32(time.Substring(0, 2));
int minute = Convert.ToInt32(time.Substring(2, 2));
int second = Convert.ToInt32(time.Substring(4, 2));
DateTime example = new DateTime(year, month, day, hour, minute, second);
Upvotes: 1
Reputation: 4181
Take a look at the Parse and ParseExact DateTime methods in the MSDN documentation.
I think that also Parsing Dates and Times in .NET can help.
Upvotes: 2
Reputation: 147224
You could use DateTime.ParseExact instead
e.g.
DateTime.ParseExact(date + hour, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture);
Upvotes: 7