Felipe Volpatto
Felipe Volpatto

Reputation: 155

Converting a string to Date

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

Answers (3)

vpp
vpp

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

Be.St.
Be.St.

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

AdaTheDev
AdaTheDev

Reputation: 147224

You could use DateTime.ParseExact instead

e.g.

DateTime.ParseExact(date + hour, "ddMMyyyyHHmmss", CultureInfo.InvariantCulture);

Upvotes: 7

Related Questions