Reputation: 6526
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
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
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 aDateTime
value whoseKind
property isDateTimeKind.Unspecified
when the method returns. If the string to be parsed contains time zone information, result contains aDateTime
value whoseKind
property isDateTimeKind.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:
2015-03-02-01
as 2015-03-02 12:00:00 AM
at timezone -01
2015-03-02 12:00:00 AM
at timezone -01
to the local timezone -05
: 2015-03-01 08:00:00 PM
Upvotes: 3
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