Не "обходите" ошибку - она не сделает то, к чему Вы хотите ее. Ошибка там на серьезном основании.
перечислимые значения инициализируются перед любыми другими статическими полями. Если Вы хотите сделать что-то как добавление всех значений в карту, сделайте это в статическом инициализаторе после все остальное:
import java.util.*;
public enum Foo
{
BAR, BAZ;
private static final Map<String, Foo> lowerCaseMap;
static
{
lowerCaseMap = new HashMap<String, Foo>();
for (Foo foo : EnumSet.allOf(Foo.class))
{
// Yes, use some appropriate locale in production code :)
lowerCaseMap.put(foo.name().toLowerCase(), foo);
}
}
}
None of your formats put the day first, like this: "dd/MM/yyyy"
.
Also note the capital 'M', since lower case 'm' is for 'minutes'. You have a similar problem with your hours; since your samples all use 24 hour time you need a capital 'H'.
Your format string array should look like this:
string[] formats = {"dd/MM/yyyy", "yyyy-MM-dd HH:mm:ss", "dd/MM/yyyy HH:mm:ss", "yyyyMMdd HH:mm:ss"};
Those formats exactly match your supplied sample strings.
Additionally, you probably want to use the invariant culture rather than en-US
in this case. Otherwise, the '/' character in your format strings is really a culture-specific date separator, which a user might over-ride on their local system.
Finally, since you're obviously having trouble matching up the strings up, you might want to use TryParseExact()
, which works just like parse exact but uses an out
parameter rather than returning the value, so that it can return a boolean to indicate success or failure rather than throwing an exception.
See the complete format string reference here:
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx