문제

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