我有一个叫TheUserTime字符串,看起来像这样:分割字符串数组在C#创建日期时间
string TheUserTime = "12.12.2011.16.22"; //16 is the hour in 24-hour format and 22 is the minutes
我想整型的数组中分割字符串来从该日期时间(会发生什么当它是0?)和组成日期对象。
这样做的最好方法是什么?
谢谢。
我有一个叫TheUserTime字符串,看起来像这样:分割字符串数组在C#创建日期时间
string TheUserTime = "12.12.2011.16.22"; //16 is the hour in 24-hour format and 22 is the minutes
我想整型的数组中分割字符串来从该日期时间(会发生什么当它是0?)和组成日期对象。
这样做的最好方法是什么?
谢谢。
您应该使用DateTime.ParseExact
或DateTime.TryParseExact
与custom format string代替。
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
}
使用TryParseExact
避免了可能的异常,如果解析失败,虽然是dt
变量将有DateTime
默认值这种情况。
我不会推荐你的方法,而是使用ParseExact
并指定预期的格式。
string theUserTime = "12.12.2011.16.22";
var date = DateTime.ParseExact(theUserTime, "MM.dd.yyyy.HH.mm", CultureInfo.CurrentCulture);
答案是好的,但我们的假设,该字符串theUserTime将被硬编码,我会建议传递变量theUserTime =的String.Format(DateTime.now.ToString( “MM.dd.yyyy.HH.mm”)); ParseExact更好,因为如果它不能解析租约,你会知道为什么,关于格式.. – MethodMan
您可以使用:
DateTime.ParseExact("12.12.2011.16.22", "MM.dd.yyyy.HH.mm", System.Globalization.CultureInfo.InvariantCulture);
好吧,感谢TryParseExact的想法,以防s#* t发生。 – frenchie
我得到了“没有重载方法TryParseExact需要4个参数;我需要改变什么? – frenchie
@frenchie - 你使用的是什么版本的.NET?看看TryParseExact的链接,它详细说明了正确的重载。错误了一个参数 – Oded