Hammad Nasir Hammad Nasir - 11 days ago 5
Android Question

Is there any way of converting time from "hh:mm:ss" format to "hh:mm AM/PM" format?

I am storing time in the database in this format:

"hh:mm:ss"
(example- 09:30:00) and then retrieving and trying to show it to users in this format: "hh:mm AM/PM" (example- 09:30 AM).

I'm using below code for converting it:

DateFormat currentTime = new SimpleDateFormat("hh:mm a");
String startTimeInSF = currentTime.format(startTime);
String endTimeInSF = currentTime.format(endTime);


where
startTime
and
endTime
is in
hh:mm:ss
format, but the above code is producing this error:
java.lang.IllegalArgumentException: Bad class: class java.lang.String
.

Please let me know how can I successfully convert the time from
hh:mm:ss
to
hh:mm AM/PM
?

Answer

I think you should parse your "hh:mm:ss" time into a Date Object, then use formatter to format it to "hh:mm a".

Like this :

    DateFormat format1 = new SimpleDateFormat("hh:mm:ss");
    try {
        Date date = format1.parse("01:11:22");
        SimpleDateFormat format2 = new SimpleDateFormat("hh:mm a");
        String result = format2.format(date);
        return result;
    } catch (ParseException e) {
        e.printStackTrace();
    }
Comments