C# 为什么TryParseExact在本例中不起作用?
我不能让它工作-它总是返回False 我错过了什么C# 为什么TryParseExact在本例中不起作用?,c#,.net,datetimeoffset,tryparse,C#,.net,Datetimeoffset,Tryparse,我不能让它工作-它总是返回False 我错过了什么 DateTimeOffset parsedDate; if ( DateTimeOffset.TryParseExact("2012-10-31 23:59:59", "YYYY-MM-dd HH:mm:ss" , CultureInfo.InvariantCulture , DateTimeStyles.None, out parsedDate) ==
DateTimeOffset parsedDate;
if ( DateTimeOffset.TryParseExact("2012-10-31 23:59:59", "YYYY-MM-dd HH:mm:ss"
, CultureInfo.InvariantCulture
, DateTimeStyles.None, out parsedDate) == false)
{
throw new ArgumentException("dateToPare", dateToParse);
}
尝试将年份设置为“yyyy”-小写
yyyy
应根据以下要求设置为小写。尝试以下操作:
[TestCase("2012-10-31 10:59:59", 2012, 10, 31, 10, 59, 59)]
[TestCase("2012-10-31 23:59:59", 2012, 10, 31, 23, 59, 59)]
public void ParseExactTest2(string dateTimeString, int year, int month, int day, int hour, int minute, int second)
{
DateTime actual = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None);
DateTime expected = new DateTime(year, month, day, hour, minute, second);
Assert.AreEqual(expected, actual);
}
正如所指出的:yyy必须是小写。
如果要引发异常,另一种方法是使用ParseExact而不是TryParseExact。使用ParseExact,您可以免费获得框架抛出的正确异常。
也许可以尝试捕获它并抛出argumentexception,其中parseexception作为innerexception