Вопрос

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