Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent FastDateFormat pattern "yyyy-MM-dd" from parsing String in format "dd-MM-yyyy"

Tags:

java

date

I have two format strings for date parsing: "yyyy-MM-dd" & "dd-MM-yyyy" and I was hoping that the FastDateFormat class would be able to distinguish between the two so that one would through a ParseException and the other would work. However both formats parse the same string values where one is obviously parsed correctly and the other is not.

My test code shows:

Parsed: "2014-06-06" into Fri Jun 06 00:00:00 EDT 2014 using "yyyy-MM-dd"
Parsed: "2014-06-06" into Sat Dec 05 00:00:00 EST 11 using "dd-MM-yyyy"
Parsed: "06-06-2014" into Sat Dec 05 00:00:00 EST 11 using "yyyy-MM-dd"
Parsed: "06-06-2014" into Fri Jun 06 00:00:00 EDT 2014 using "dd-MM-yyyy"

Is there any easy way to make FastDateFormat handle the 4 digit year properly based upon the pattern?" I don't see any lenient settings on FastDateFormat.

like image 821
Awk Omo Avatar asked Sep 29 '14 20:09

Awk Omo


1 Answers

I can reproduce your results with Apache-Common-Lang-library. It seems the API does not offer any official solution, also not in newest version v3.3.2. Normally a good parser would reject the input 2014-06-06 for the pattern dd-MM-yyyy by throwing an exception but here FastDateFormat tolerates it and cannot even be set to non-lenient mode like SimpleDateFormat.

So the only options left are:

a) Do your own hack (similar to following code example):

public class ParserDDMMYYYY extends FastDateFormat {
  public static final INSTANCE = 
    new ParserDDMMYYYY("dd-MM-yyyy", TimeZone.getDefault(), Locale.getDefault());

  @Override
  public Date parse(String input) throws ParseException {
    if (input.charAt(4) == '-') {
      throw new ParseException("Invalid format: " + input, 0);
    }
    return super.parse(input);
  }

  // ... more overrides of similar parse methods
}

The case of preventing dd-MM-yyyy for the pattern yyyy-MM-dd is very similar.

b) Or you change the date-time-library since there are at least three better libraries around for date-time-handling and formatting. Keep in mind that the apache-library is still based on old java.util.*- and java.text.*-packages.

I also doubt if the class FastDateFormat is really so much better in performance, surely not better compared with the immutable versions of other date-time-libraries. For example I have seen some synchronized-keywords in the apache library (potential lock competition, not so modern).

like image 61
Meno Hochschild Avatar answered Oct 19 '22 04:10

Meno Hochschild