Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a DateFormatter which converts a two-digit year into a four-digit year?

Tags:

java

calendar

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?

like image 463
Daniel Rikowski Avatar asked Feb 28 '11 15:02

Daniel Rikowski


3 Answers

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

like image 116
josh.trow Avatar answered Sep 30 '22 18:09

josh.trow


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
like image 29
Mike Yockey Avatar answered Sep 30 '22 18:09

Mike Yockey


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.

like image 37
G B Avatar answered Sep 30 '22 16:09

G B