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

In my Java application, I use an instance of DateFormat to parse date entries.

 DateFormat fmt; fmt = DateFormat.getDateInstance(DateFormat.DEFAULT) // dd.MM.yyyy for de_DE 

The problem is that the user insists on entering dates in the form 31.12.11 .

Unfortunately, this is being analyzed on 31.12.11 . ( 0011-12-31 in ISO format) Instead, I want the syntax date to be 31.12.2011 ( 2011-12-31 in ISO format).

Can I change the date format to somehow parse the input in this way?

+7
source share
6 answers

You will need to parse the dd.MM.yy format and reformat it in the yyyy-MM-dd format

 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 information on setting up templates.

http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html

+11
source

Your solution here is simple enough to use SimpleDateFormat, which includes the set2DigitYearStart(Date startDate) method. 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 
+5
source

Yes, you can parse using DateFormat.SHORT instead of DEFAULT.

Or maybe try parsing with SHORT, and then try other formats if that doesn't work.

+1
source

You can analyze this date using SimpleDateFormat, but how will you determine if it was 1911 or 2011 or something else. you must use the year format as yyyy.

+1
source

If you use GWT, you do not have access to SimpleDateFormat, so here is some code to do this manually:

 String[] parts = dateText.split(" "); // Convert 2 digit date to 4 digits if (parts.length == 3 && parts[2].length() == 2) { int year = Integer.valueOf(parts[2]); // Allow 5 years in the future for a 2 digit date if (year + 100 > new Date().getYear()+5) { year = year + 1900; } else { year = year + 2000; } dateText = parts[0] + " " + parts[1] + " " + String.valueOf(year); } 

This assumes that you have confirmed that dateText is separated by spaces.

+1
source

Approximation:

 int twoDigitYear = 11; int fourDigitYear = 0; DateTime now = new DateTime(); if (twoDgYear + 2000 > now().getYear()) { fourDigitYear = twoDigitYear + 1900; }else{ fourDigitYear = twoDigitYear + 2000; } 

May or may not match your need ...

0
source

All Articles