DateTime.ParseExact date format continues to throw an error

I have a string representation of a DateTime that looks like this:

2011-05-25T16:42:17.156Z

I tried the following with no luck:

DateTime.ParseExact(formatted, "yyyy-MM-ddThh:mm:ss.fffZ", CultureInfo.CurrentCulture);
DateTime.ParseExact(formatted, "yyyy-MM-dd hh:mm:ss.fff", CultureInfo.CurrentCulture);
DateTime.ParseExact(formatted, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);
DateTime.ParseExact(formatted, CultureInfo.CurrentCulture.DateTimeFormat.GetAllDateTimePatterns(), CultureInfo.CurrentCulture, DateTimeStyles.None);

All of them give an error:

String was not recognized as a valid DateTime.

The standard DateTime.Parse function works, although for performance reasons we are exploring ParseExact. It seems to be pretty straight forward, but it seems it can't make it work.

+3
source share
1 answer

Use HH instead of hh for 24 hour format. This should work:

DateTime.ParseExact(formatted, "yyyy-MM-ddTHH:mm:ss.fffZ",
                    CultureInfo.CurrentCulture);

Are you sure you want to use the current culture, not invariant culture?

+6
source

All Articles