简体   繁体   中英

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.

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);

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 .

您可以使用:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM