0
public static String getTime(String time) {

    String ampmTime = null;
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss", Locale.getDefault());
    Date dt;
    try {
        dt = sdf.parse(time);
        SimpleDateFormat sdfs = new SimpleDateFormat("hh:mm a", Locale.getDefault());
        if (dt != null) {
            ampmTime = sdfs.format(dt);
        }

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return ampmTime;
}

In parameter string i'm sending 12:00:00 format so please i want this as 12:00pm instead of 12:00am . And others time is showing correctly like 13:30:00 to 1:30pm . So please help me??

  • Please consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends. See if you either can use [desugaring](https://developer.android.com/studio/write/java8-support-table) or add [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project, in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Sep 21 '21 at 20:18
  • `LocalTime.parse("12:00:00").format(DateTimeFormatter.ofPattern("hh:mm a", Locale.forLanguageTag("en-IN")))`. Yields `12:00 PM` as requested. Yes, it’s true, with java.time you only need one formatter. Please break up into appropriate number of statements yourself. – Ole V.V. Sep 21 '21 at 20:29

1 Answers1

1

As stated here, When using hh you are telling the formatter the input time is an am/pm time. Use HH for 24hrs input.

Change the format to:

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
gioravered
  • 1,758
  • 3
  • 19
  • 30