frenchie
frenchie

Reputation: 51937

splitting string to array to create dateTime in c#

I have a string called TheUserTime that looks like this:

string TheUserTime = "12.12.2011.16.22"; //16 is the hour in 24-hour format and 22 is the minutes

I want to generate a DateTime from this by splitting the string in a array of ints (what happens when it's 0?) and composing the date object.

What's the best way to do this?

Thanks.

Upvotes: 1

Views: 1243

Answers (3)

Oded
Oded

Reputation: 499012

You should use DateTime.ParseExact or DateTime.TryParseExact with a custom format string instead.

ParseExact:

DateTime.ParseExact("12.12.2011.16.22", "dd.MM.yyyy.HH.mm", 
                    CultureInfo.InvariantCulture)

TryParseExact:

DateTime dt;
if(DateTime.TryParseExact("12.12.2011.16.22", "dd.MM.yyyy.HH.mm",
                          CultureInfo.InvariantCulture, DateTimeStyles.None, 
                          out dt))
{
  // parse successful use dt
}

Using TryParseExact avoids a possible exception if the parse fails, though is such a case the dt variable will have the default value for DateTime.

Upvotes: 6

Mike Christensen
Mike Christensen

Reputation: 91618

You can use:

DateTime.ParseExact("12.12.2011.16.22", "MM.dd.yyyy.HH.mm", System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 0

Anthony Pegram
Anthony Pegram

Reputation: 126864

I would not recommend your approach, but instead use ParseExact and specify the expected format.

string theUserTime = "12.12.2011.16.22";
var date = DateTime.ParseExact(theUserTime, "MM.dd.yyyy.HH.mm", CultureInfo.CurrentCulture);

Upvotes: 5

Related Questions