In my Java application I use a DateFormat
instance to parse date inputs.
DateFormat fmt;
fmt = DateFormat.getDateInstance(DateFormat.DEFAULT) // dd.MM.yyyy for de_DE
The problem is that the user insists to enter dates in the form 31.12.11
.
Unfortunately this is parsed to 31.12.11
. (0011-12-31
in ISO format) Instead I want the parsed date to become 31.12.2011
(2011-12-31
in ISO format).
Can I modify the date format to somehow parse inputs that way?
You will have to parse with a format of dd.MM.yy and re-format with a format of yyyy-MM-dd
DateFormat sdfp = new SimpleDateFormat("dd.mm.yy");
Date d = sdfp.parse(input);
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd");
String date = sdff.format(d);
See the Java API for more info on setting patterns.
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
Your solution here is sufficiently simple as to allow for the use of SimpleDateFormat, which includes the method set2DigitYearStart(Date startDate)
. Perhaps it looks something like this.
String userInput = "31.12.11";
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yy");
format.set2DigitYearStart(new GregorianCalendar(2001,1,1).getTime());
Date userEnteredDate = format.parse(userInput, 1); // parsed to 2011-12-31
Yes, you could parse using DateFormat.SHORT instead of DEFAULT.
Or possibly, try to parse with SHORT, and then try other formats if that doesn't work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With