SimpleDateFormat Return wrong value

Viewed 38

I have two different date format from multiple source i want to format but its return wrong value.

    String d1 = getFormattedDate("06-07-2022 18:37:01");
    String d2 = getFormattedDate("2020-11-21 18:45:15");
    System.out.println(d1);
    System.out.println(d2);

private static String getFormattedDate(String date) {
    try {
        SimpleDateFormat targetSdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf1.parse(date);
            return targetSdf.format(date1);
        } catch (Exception e) {
            SimpleDateFormat sdf5 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date5 = sdf5.parse(date);
            return targetSdf.format(date5);
        }
    } catch (Exception e) {

    }
    return date;
}

and output is

12/01/0012 06:37:01 PM

21/11/2020 06:45:15 PM

could you please help me to fix it

1 Answers

your input on day 1 is malformed, it should be yyyy-MM-dd, but you pass as dd-MM-yyyy. Code here

private static String getFormattedDate(String date) {
    try {
        SimpleDateFormat targetSdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date1 = sdf1.parse(date);
            return targetSdf.format(date1);
        } catch (Exception e) {
            SimpleDateFormat sdf5 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            Date date5 = sdf5.parse(date);
            return targetSdf.format(date5);
        }
    } catch (Exception e) {

    }
    return date;
}
public static void main(String[] args) throws ParseException {
    String d1 = getFormattedDate("2022-07-06 18:37:01");
    String d2 = getFormattedDate("2020-11-21 18:45:15");
    System.out.println(d1);
    System.out.println(d2);

}
Related