Thomas Kowalski
Thomas Kowalski

Reputation: 2184

Using DateTime.ParseExact throws format exception

I know the question is really asked often, but I can't find the solution to my problem. My code is

Public Function ConvertFacebookDateToNETDate(Instant As String, Format As String) As Date
    'Dim UTCOffset As New Integer
    'UTCOffset = Instant.Substring(Instant.IndexOf("UTC+") + 4, 2)

    Dim MyDateTime As DateTime
    MyDateTime = New DateTime()
    MyDateTime = DateTime.ParseExact(Instant, Format, CultureInfo.InvariantCulture)
    'MyDateTime = MyDateTime.AddHours(-1 * UTCOffset)
    Return MyDateTime
End Function

ConvertFacebookDateToNETDate("Friday, May 9, 2014 at 9:48am UTC+02", "dddd, MMMM d, yyyy at h:mtt UTCK")

What is going wrong here ?

Thanks

Upvotes: 0

Views: 115

Answers (2)

Sehnsucht
Sehnsucht

Reputation: 5049

Two things (all the info comes from there):

  • In your format you put "at" but "t" if a format specifier so you have to escape it "a\t" or put it between literal delimiter "'at'"
  • The "K" format specifier for a DateTime with Kind local (a "±XX") needs to be "±XX:XX" so you have to either pass a Date string with that pattern or use "zz" format specifier instead of "K"

Upvotes: 2

Guffa
Guffa

Reputation: 700562

There are two problems with the data format

  • The t in at is interpreted as the short form of tt, i.e. the first character of AM/PM designator. You need to escape it to specify that it's a literal character.
  • The specifier for time zone offset in hours is z, not K.

So:

ConvertFacebookDateToNETDate("Friday, May 9, 2014 at 9:48am UTC+02", "dddd, MMMM d, yyyy' at 'h:mtt UTCz")

Upvotes: 1

Related Questions