Unbreakable Unbreakable - 10 months ago 83
Vb.net Question

Format Exception when trying to get date in VB.Net

Can some one guide me on why I am getting this error. I have tried many permutations but I am not able to parse the string and get the date out of it

Public Function Starter(starterInput As LoginUserResponse) As List(Of GraphDataObj) Implements iSMS_Rest.Starter
Dim _currentUser = System.Web.HttpContext.Current.Cache(starterInput.tokenProp)
Dim res As Date
Dim provider As Globalization.CultureInfo = Globalization.CultureInfo.InvariantCulture
Dim dateString As String
dateString = starterInput.dateProp // VALUE HERE: "2016-08-31T03:59:59.000Z"
res = Date.ParseExact(dateString, "dd/MM/yyyy", provider)
'SOME CODE
End Function


Exception I am getting

enter image description here

I looked into this link for help: Convert a string to a datetime

Answer

The value you're using is:

"2016-08-31T03:59:5‌​9.000Z"

Which is not the format:

"dd/MM/yyyy"

It sounds like ParseExact isn't what you're looking for. The input format is a very common date format and will be understood by simply using Parse:

res = Date.Parse(dateString, provider)

(Or, if you don't trust the consistency of the format from the value being provided, you can also use Date.TryParse() instead.)