5

Can anyone see what I'm doing wrong here? The Assert.IsTrue(parses) always fails.

    [TestMethod]
    public void Can_Parse_To_DateTime()
    {
        DateTime expected = new DateTime(2011, 10, 19, 16, 01, 59);
        DateTime actual;

        string value = "Wed Oct 19 16:01:59 PDT 2011";
        string  mask = "ddd MMM dd HH:mm:ss xxx YYYY";

        bool parses = DateTime.TryParseExact(value, mask, 
                                             CultureInfo.InvariantCulture, 
                                             DateTimeStyles.None, 
                                             out actual);

        Assert.IsTrue(parses);
        Assert.AreEqual(expected, actual);
    }

I have also tried it thus, with the same result:

    [TestMethod]
    public void parsing()
    {
        DateTime expected = new DateTime(2011, 10, 19, 16, 01, 59);
        DateTime actual;

        string value = "Wed Oct 19 16:01:59 PDT 2011";
        string  mask = "ddd MMM dd HH:mm:ss YYYY"; // note removal of "xxx "

        value = value.Remove(20, 4);  // removal of the "PDT "
        bool parses = DateTime.TryParseExact(value, mask, 
                                             CultureInfo.InvariantCulture, 
                                             DateTimeStyles.None, 
                                             out actual);

        Assert.IsTrue(parses);
        Assert.AreEqual(expected, actual);
    }
Scott Baker
  • 10,013
  • 17
  • 56
  • 102

2 Answers2

3

As noted by Matt Hamilton, yyyy must be lowercase. And xxx is totally invalid. You can always test your format string using reverse method DateTime.ToString(format,CultureInfo.InvariantCulture).

Al Kepp
  • 5,831
  • 2
  • 28
  • 48
  • According to this previous question you can replace timezone string with timezone offset and it will work - http://stackoverflow.com/questions/241789/parse-datetime-with-timezone-of-form-pst-cest-utc-etc – Paige Cook Oct 20 '11 at 01:12
  • Really like that you gave the option to try a reverse check. It hadn't occurred to me when I had similar pains. Still not a total fix for the OP, but a step in the right direction. – Tim Meers Oct 20 '11 at 01:37
1
 string mask = "ddd MMM dd HH:mm:ss PDT yyyy";
ojlovecd
  • 4,812
  • 1
  • 20
  • 22