BateTech
BateTech

Reputation: 6526

Date.TryParse incorrect results

When using Date.TryParse, why would a string input of "2015-03-02-01" succeed during conversion from string to Date, with result of "3/1/2015 8:00:00 PM"? Using VS2013 targeting .NET 4.0.

I would expect Date.TryParse to return false in this case.

If it did succeed, I would expect it to return with either

  1. "3/2/2015" ignoring the final "-01"
  2. "3/1/2015 11:00:00 PM" if it treated the final "-01" as minus one hour from "2015-03-02"
  3. "3/1/2015 7:00:00 PM" if it treated the final "-01" as minus one hour and then applied the current US Eastern Daylight Time UTC offset of -4 as well.

Any idea of what is going on here internally that would cause it to return "3/1/2015 8:00:00 PM"?

Here is a test case:

<TestMethod()>
Public Sub TestDateTryParse()
    Dim s As String = "2015-03-02-01"
    Dim d As Date
    If Date.TryParse(s, d) Then
        Assert.Fail("Date parsed when should have failed. Input: ""{0}"", Output: ""{1}""", s, d)
    End If
End Sub

Test Result Message: Assert.Fail failed. Date parsed when should have failed. Input: "2015-03-02-01", Output: "3/1/2015 8:00:00 PM"

Upvotes: 1

Views: 159

Answers (2)

sstan
sstan

Reputation: 36513

The string is interpreted as 2015-03-02 at timezone -01.

The documentation for DateTime.TryParse has this to say:

If s contains no time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Unspecified when the method returns. If the string to be parsed contains time zone information, result contains a DateTime value whose Kind property is DateTimeKind.Local when the method returns.

So, for a very normal date string like 2015-03-02, when you parse it using DateTime.TryParse(), you will see that the date's Kind property will be DateTimeKind.Unspecified as documented.

But if you check the Kind property in your funny case, you will see that it will give you DateTimeKind.Local, indicating that the parsing operation detected timezone information.

So what happens in this case is that your local timezone must be -05. (EDIT: or more precisely, was -05 on 2015-03-02. Because of daylight savings time, your current timezone may be different, but the timezone that matters is the one that was in effect on 2015-03-02) So when it parses 2015-03-02-01, here is what it does:

  • Interpret 2015-03-02-01 as 2015-03-02 12:00:00 AM at timezone -01
  • Convert 2015-03-02 12:00:00 AM at timezone -01 to the local timezone -05: 2015-03-01 08:00:00 PM

Upvotes: 3

Blackwood
Blackwood

Reputation: 4534

The "-01" at the end of your string is being interpreted as a time zone offset from UTC (more commonly known as GMT).

Upvotes: 3

Related Questions