All used formats can be grouped and a method can be written to check each date against all formats. But check if the nd, th, rd, can be generally named something like 'xx' so that the parser ignores it.
I hope the above approach will cause the problem in some conditions. Specially when the date is less than 10. for example 08-08-2011(There is no guaranty that this is in dd-mm-yyyy or mm-dd-yyyy format). Hence write a method to parse the date along with send the format you want to convert. Please ignore if i am wrong
John Jai wrote:All used formats can be grouped and a method can be written to check each date against all formats. But check if the nd, th, rd, can be generally named something like 'xx' so that the parser ignores it.
You don't need to catch any exceptions if you use the other parse method:
This behaviour is consistent with other Java classes in general. I don't understand why the designer would have one class thowing exception while the other returns null even though they both achieve the same objective, but that is besides the point.
Crystal clear now. Thanks again,
posted 7 years ago
The suggestion by Jon Thai & Rob Spoor does not work when the date of the month is more than 1 digit. For instance where the string date is "22nd December 2011". Below is an enhancement intended to overcome this limitation but failed to work:
The value of publishedDate is null as opposed to 22-12-2911.
Any idea on where the problem is coming from? I am not clear on how line 2 - 7 work.
If I take that code and that example input String, I get successfully parsed dates for the third and fourth patterns.
As for the working of that code:
- Line 2 creates a ParsePosition object that will be shared for all parsing. A ParsePosition contains two important values: the current index and the index of where the last error occurred. This one's initialized with a current index of 0 (start of String), and the error index defaults to -1 (no error).
- Line 3 iterates over all of the formats.
- Lines 4 and 5 reset the ParsePosition, because it may have been modified by a call of line 7 of a previous iteration.
- Line 6 is comment
- Line 7 creates a SimpleDateFormat object with the current format, and tries to parse the input String to a Date. If it fails the ParsePosition's error index is updated and the parse method returns null. If it succeeds the ParsePosition's index is updated instead and the parse method returns the result.