In one of my projects I received a requirement that stated that while parsing a text file Strings denoting a date or a timestamp are expected to be in many different formats that are not known in advance, yet all of them that represent a valid date or timestamp need to be parsed properly. So the solution I came up with is to have a set of formats stored in property file, and when a String needs to be parsed the formats are read from a file and attempts to parse the String are made sequentially with each format until it is parsed successfully or until we run out of formats. The advantages of this solution are that if you discover a valid String that was not parsed successfully, all you will need to do is to add new format to your properties file and no re-compilation and re-deployment is needed. Also this way you can set your priorities: say if US date format is preferable to European one just place US formats first and only after the European ones. Also in java 8 the format strings allow for optional format sections denoted by ''. So several formats actually may be combined into a single one with optional sections. For example instead of
you can just write
So, below is my set of formats that I found to cover a wide range of valid date formats. This set of course does not cover ALL possible formats. For instance it does not cover an option that date includes milliseconds. But I think it is a good set to start with if you ever have such requirement. so here it is:
Setting "priorities" sounds like a good idea but it's really an assumption that shouldn't be made in some cases. For example if I give you "02-03-2016" your priorities might assume something contrary to what I actually meant. So perhaps it would be an improvement to (optionally) collect all possible dates produced by the multi-parsing and do something different if that set's size is greater than one?