This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I'm having a hard time parsing dates that are entered in different formats. Is there a general way to do that? I have a text field where the user can enter a date (so obviously he can enter any format) ex.
or the date can be invalid (505002 or anything else)
Is there a general approach on how to handle things like that? i found the classes simpledateformatter and dateformatter, but they can handle only one format.
The best way would probably be to not let the user enter the date via a text field. That way you can more easily control the format of the date entered. If this is a swing app, you could possibly use a JComboBox to constrain the possible inputs.
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Use a number of allowed formats, then check each of them:
The order is quite important here; if MM/dd/yyyy comes before dd/MM/yyyy then 01/02/2010 will be January 2nd. If the order is the other way around then it's February 1st.
This is not a simple problem for which there is a simple solution, because there are numerous ways to enter a date in an ambiguous way.
For example, what if I enter "020310"? Does that mean 2 March 2010 (ddmmyy), 3 February 2010 (mmddyy), 10 March 2002 (yymmdd) or some other possible combination? You'll have to think about what inputs you're going to accept and how the different possibilities should be interpreted.
There's no standard method in the standard Java library to parse any "arbitrary format" string into a date.
No. In fact, in the current implementation parse(String) calls parse(String, ParseException), then either returns the parsed Date or throws a ParseException:
By the way, these two fields of ParsePosition have package visibility; we must use the matching getters and setters.