Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make DateFormat guess intended century?

Tags:

java

datetime

I am trying to parse a String in "dd-MM-yy" format to a Date object. The problem is that it tries to guess the century for the date.

When specified from 01 to 31, year is interpreted as 2000s (21st Century) and 32 t0 99 is considered 1900s (20th Century).

SimpleDateFormat fm =new SimpleDateFormat("dd-MM-yy");
String datestr="21-11-31";
try {
  Date date= fm.parse(datestr);
  System.out.println(date);
} catch (ParseException e) {
}

Can anyone help me? How can I specify that I am only working in the 21st Century neatly. I am not exactly trying to look for tricks like manipulating the string or shifting the date based on the condition.

like image 940
Edge Avatar asked May 24 '12 06:05

Edge


People also ask

How to format a date using SimpleDateFormat?

SimpleDateFormat can be created using the SimpleDateFormat constructor. The constructor is a parametrised constructor and needs a String pattern as the parameter. The String pattern is the pattern which will be used to format a date and the output will be generated in that pattern as “ MM-dd-yyyy ”.

What is the difference between DateFormat and SimpleDateFormat?

The java SimpleDateFormat allows construction of arbitrary non-localized formats. The java DateFormat allows construction of three localized formats each for dates and times, via its factory methods.

How will you format a date based on a locale after you have obtained a DateFormat object?

To format a date for the current Locale, use one of the static factory methods: myString = DateFormat. getDateInstance(). format(myDate);


1 Answers

You can change the century it uses to interpret 2 digit data entry with the set2DigitYearStart() method.

SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String aDate = "03/17/40";
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, 2000);
dateFormat.set2DigitYearStart(cal.getTime());
System.out.println(dateFormat.get2DigitYearStart());
System.out.println(dateFormat.parse(aDate));

Will print March 17, 2040.

like image 62
Affe Avatar answered Oct 06 '22 00:10

Affe