简体   繁体   English

将字符串拆分为数组以在C#中创建dateTime

[英]splitting string to array to create dateTime in c#

I have a string called TheUserTime that looks like this: 我有一个名为TheUserTime的字符串,如下所示:

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. 我想通过将字符串拆分为一个int数组(当它为0时会发生什么?)并组成date对象,由此生成DateTime。

What's the best way to do this? 最好的方法是什么?

Thanks. 谢谢。

I would not recommend your approach, but instead use ParseExact and specify the expected format. 我不推荐您使用的方法,而是使用ParseExact并指定所需的格式。

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. 您应该使用带有自定义格式字符串的 DateTime.ParseExactDateTime.TryParseExact

ParseExact : ParseExact

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

TryParseExact : 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 . 如果解析失败,使用TryParseExact可以避免可能的异常,尽管在这种情况下dt变量将具有DateTime的默认值。

您可以使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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