I want to build an application that will receive user-defined Strings of unknown size and identify them as either being simple Strings or dates. What I want to do is to find a way to extract the date pattern of the String without knowing if the String that the program will receive will actually be a date.
More precisely, if the String that will be received is going to be
"2014-05-07_0533" //valid date
the program will return
"yyyy-MM-dd_HHmm"
But if the String that is going to be received is
"2014-05_667788" //not a valid date
the program will raise an Exception or otherwise inform the user that the supplied String does not follow a known date pattern, thus it's not a date. One way that I can think of implementing the previous problem is declaring a predefined List
of available date patterns which the program will accept and then exhaustively trying to match the supplied String with each one of these patterns. When there is a match, the program will return the matched pattern. If none of the available patterns are matched, null
or a message will be returned.
The problem with the above thought is that the Strings that the program will receive are going to be scaled up to tens or hundreds of thousands, so I'm starting to think that this method will have significant impact on the application's speed and overall memory footprint. Is there a better solution?
EDIT
There is no code so far, as I am in the early stages of development and I'm just running some ideas on how to implement it.
EDIT2
For those of you who request a code sample, this is what I have thought so far:
public class DateMatching {
public List<String> datePatterns = new ArrayList<>();
public DateMatching() {
initializePatterns();
}
private void initializePatterns() {
datePatterns.add("yyyy-MM-dd_HH:mm");
datePatterns.add("yyyy/MM/dd_HH:mm");
datePatterns.add("yyyy.MM.dd_HH:mm");
//and so on...
}
public final String getDatePattern(String supplied) {
DateFormat format;
for(String datePattern : datePatterns) {
format = new SimpleDateFormat(datePattern);
try {
format.parse(supplied);
return datePattern;
} catch(ParseException e) {
continue;
}
}
return null; //No matched pattern
}
}
As the datePatterns
list could contain up to 50 or more patterns and the Strings that the application will receive may be more than tens or hundreds of thousands, I'm trying to find a way to reduce the amount of time the matching process will require for all these Strings -assuming that there is one, to begin with.