Question

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);
}
Was it helpful?

Solution

yyyy should be lower-cased, according to MSDN.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top