Question

I have an issue with converting a date time value to expected one with SimpleDateFormat (java), my expected format is MM/yyyy, and I want to convert 2 values to only 1 format

  1. MM-yyyy for example 05-2012
  2. yyyy-MM for example 2012-05

ouput is 05/2012.

I implemented something look like following

String expiry = "2012-01";
try {
    result = convertDateFormat(expiry, "MM-yyyy", expectedFormat);
} catch (ParseException e) {
    try {
        result = convertDateFormat(expiry, "yyyy-MM", expectedFormat);
    } catch (ParseException e1) {
        e1.printStackTrace();
    }
    e.printStackTrace();
}

private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException {
    SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern);
    Date d = normalFormat.parse(date);
    SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern);
    return cardFormat.format(d);
}

Now, the return value is 6808, I don't know why.

Kindly anyone help me on this case.

Was it helpful?

Solution

Add SimpleDateFormat#setLenient() to your convertDateFormat method:

private String convertDateFormat(String date, String oPattern, String ePattern) throws ParseException {
    SimpleDateFormat normalFormat = new SimpleDateFormat(oPattern);
    normalFormat.setLenient(false); /* <-- Add this line -- */
    Date d = normalFormat.parse(date);
    SimpleDateFormat cardFormat = new SimpleDateFormat(ePattern);
    return cardFormat.format(d);
}

It will make the convertDateFormat fail if the date is incorrect.

This is explained in detail here: http://eyalsch.wordpress.com/2009/05/29/sdf/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top