-1

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?

Hammad Nasir
  • 2,889
  • 7
  • 52
  • 133

3 Answers3

3

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();
    }
lomg
  • 136
  • 2
1

I believe you're looking for the parse(String source) method. The format() methods take in a Date object and output a String representation of the object. the parse methods take in a String object and converts it to a Date object.

To do what you want, you'll need to have a DateFormat with hh:mm:ss, convert the database String to a Date using parse, and then use your existing DateFormat and use format on the Date object to get the output String to display to your user.

http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html

cameronlund4
  • 537
  • 1
  • 5
  • 27
0

You need to change your code something like this, format function will not work directly on String object that is root cause of your exception.

DateFormat inputFormatter1 = new SimpleDateFormat"HH:mm:ss");
        Date date1 = inputFormatter1.parse("22:10:11");

        DateFormat outputFormatter1 = new SimpleDateFormat("hh:mm a");
        String output1 = outputFormatter1.format(date1); //

Out will be 10:10 pm

Swapnil
  • 2,409
  • 4
  • 26
  • 48