Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this DateTime parse always fail?

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);
    }
like image 370
Scott Baker Avatar asked Oct 09 '22 17:10

Scott Baker


1 Answers

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).

like image 160
Al Kepp Avatar answered Oct 13 '22 10:10

Al Kepp