Search code examples
javadateexceptionsimpledateformatdate-parsing

Format and parsing same date provides different result


Could anybody please tell me why I'm getting "10/09/2022" on the console?

String sFecha = "10/21/2021";
try {
   SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
   System.out.println(sdf.format(sdf.parse(sFecha)));
} catch (java.text.ParseException e) {
   //Expected execution
}

Note: the input string is intentionally wrong - I am expecting the Exception!


Solution

  • java.time

    The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

    The problem you have observed with your code is one of the weird problems that you face with SimpleDateFormat. Instead of throwing the exception because of the wrong format, SimpleDateFormat tries to parse the date string erroneously.

    Solution using java.time, the modern Date-Time API:

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.format.DateTimeParseException;
    
    public class Main {
        public static void main(String[] args) {
            String sFecha = "10/21/2021";
            try {
                DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                LocalDate date = LocalDate.parse(sFecha, dtf);
                System.out.println(date);
            } catch (DateTimeParseException e) {
                System.out.println("A problem occured while parsing the date string.");
                // ...Handle the exception
            }
        }
    }
    

    Output:

    A problem occured while parsing the date string.
    

    Now, change the format to MM/dd/yyyy and you will see that the date string will be parsed successfully.

    Learn more about the modern Date-Time API from Trail: Date Time.

    In case you want to use SimpleDateFormat:

    Pass false to SimpleDateFormat#setLenient which is set true by deafult.

    Demo:

    import java.text.SimpleDateFormat;
    
    public class Main {
        public static void main(String[] args) {
            String sFecha = "10/21/2021";
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
                sdf.setLenient(false);
                System.out.println(sdf.format(sdf.parse(sFecha)));
            } catch (java.text.ParseException e) {
                System.out.println("A problem occured while parsing the date string.");
                // ...Handle the exception
            }
        }
    }
    

    Output:

    A problem occured while parsing the date string.
    

    * If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring. Note that Android 8.0 Oreo already provides support for java.time.