Вопрос

I am trying to parse a TimeString that looks like:

11/Apr/2014:00:00:12 +0200

my code looks like

DateTime.ParseExact("11/Apr/2014:00:00:12 +0200", "dd/MMM/yyyy:HH:mm:ss zzz", null)

I looked at the MSDN and it looks good for me but I have no clue why I always get a FormatException.

Это было полезно?

Решение

You should add the InvariantCulture as a format provider.

var d = DateTime.ParseExact("11/Apr/2014:00:00:12 +0200", "dd/MMM/yyyy:HH:mm:ss zzz", CultureInfo.InvariantCulture);

Your format string is considering that the / and : characters are specific format separators that will resolve to the ones defined in your current culture, just as HH would signify "hours" in your format. Please refer to this page to see that the time separator and date separator are predefined and will be replaced by the culture specific values.

It is possible to escape the special characters but I think that in the long run your code will be much safer with the InvariantCulture

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top