I need to match a given date against 5 different format. How can I do
this ?
The predefined date formats are :-
Format 1 - yyyy MMM dd hh:mm:ss a
Format 2 - yy-MM-dd hh:mm:ss
Format 3 - MMM dd yyyy hh:mm
Format 4 - dd MMM yyyy hh:mm
Format 5 - dd-MM-yy hh:mm
and If I get a date "2007 Jul 14 10:21:19 am", I need to pick the
first option ie., Format 1.
How can I go about this ? Is there any API which can determine the
date format of a string? Any help is appreciated.
-Aparna
Mark Bryan Yu - 14 Jun 2007 20:27 GMT
Here's a quick and dirty solution:
SimpleDateFormat[] formatters = new
SimpleDateFormat[5];
formatters[0] = new SimpleDateFormat("yyyy MMM dd hh:mm:ss a");
formatters[1] = new SimpleDateFormat("yy-MM-dd hh:mm:ss");
formatters[2] = new SimpleDateFormat("MMM dd yyyy hh:mm");
formatters[3] = new SimpleDateFormat("dd MMM yyyy hh:mm");
formatters[4] = new SimpleDateFormat("dd-MM-yy hh:mm");
String date = "07-07-14 10:21:19";
boolean found = false;
for (int i = 0; i < formatters.length; i++) {
try {
formatters[i].parse(date);
System.out.println("Pattern " + (i+1));
found = true;
break;
} catch (Exception e) {
}
}
if (!found) {
System.out.println("No format found.");
}
> I need to match a given date against 5 different format. How can I do
> this ?
[quoted text clipped - 13 lines]
>
> -Aparna
Martin Gregorie - 14 Jun 2007 22:34 GMT
> I need to match a given date against 5 different format. How can I do
> this ?
[quoted text clipped - 13 lines]
>
> -Aparna
Last time I needed to do this, a very long time ago, the requirement was
to accept a very wide variety of possible date formats (these included,
but were not limited to, dates like 23Jan90, 1586, 55BC, 1Q/07) with the
requirement that any valid date must be output in the format it had been
input in and must be capable of being compared to any other date. I used
a set of steps to recognize the formats:
- made a copy of the input
- modified the copy by replacing all digits with 9, all letters with X
and multiple spaces with a single space
- compared the string with a set of pattern strings until I got a match
- used the matching pattern reference to extract ccyyddmm from the
original input.
- check that the ccyyddmm string was a valid date and the input format
was permitted for the input field
- store both the date and the pattern reference.
It may be possible to use standard Java date formats as recognition
patterns as well as conversion templates. However, pattern recognition
may may be easier with the more basic Xs and 9s.

Signature
martin@ | Martin Gregorie
gregorie. | Essex, UK
org |