0

My code is as shown below:

private String getFormattedDate(String date){
    try {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date value = formatter.parse(date);

        SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM HH:mm a");

        dateFormatter.setTimeZone(TimeZone.getDefault());
        date = dateFormatter.format(value);

    } catch (Exception e) {
        date = "00-00-0000 00:00";
    }

    return date;
}

Here what I want to do is , I want to convert 2018-03-19T19:24:41.396Z into the format 19-03 7:24 PM, but here it gives me the output 19-03 19:24 PM . Am I missing anything in my method because of which it is giving the false output?

Mrugesh
  • 4,381
  • 8
  • 42
  • 84
  • note the returned date in the catch block doesn't have the same format than the date in the try block – jhamon Mar 20 '18 at 11:07

3 Answers3

2

SimpleDateFormat

Capital H Hour in day (0-23) and Small h Hour in am/pm (1-12)

Change this line

  SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM HH:mm a");

to

  SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM hh:mm a");
Lucifer
  • 29,392
  • 25
  • 90
  • 143
1

HH outputs hour in 0-23 format. You must use hh instead.

Psytho
  • 3,313
  • 2
  • 19
  • 27
1

Try This

            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date value = formatter.parse(date);

            SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM hh:mm a");

            dateFormatter.setTimeZone(TimeZone.getDefault());
            date = dateFormatter.format(value);
            System.out.println("Date :- "+date);
Lucifer
  • 29,392
  • 25
  • 90
  • 143
Amit Singh
  • 77
  • 1
  • 8