Reputation: 51937
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
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
Reputation: 91618
You can use:
DateTime.ParseExact("12.12.2011.16.22", "MM.dd.yyyy.HH.mm", System.Globalization.CultureInfo.InvariantCulture);
Upvotes: 0
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