I cannot make this work -it always returns False.

What do I miss here?

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 should be lower-cased, according to MSDN.

其他提示

Try with year as "yyyy" - lower case

Try this:

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

As pointed out: yyyy must be lower case. An alternative is to use ParseExact instead of TryParseExact if you are going to throw an exception. Using ParseExact you get the correct exception thrown by the framework for free. Maybe try catch it and throw your argumentexception withh the parseexception as innerexception.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top