How to convert 24 hr format time in to 12 hr Format?

For someone with lower api version, work well with 12:00 AM or PM and min < 10

  String time =  ((hourOfDay > 12) ? hourOfDay % 12 : hourOfDay) + ":" + (minute < 10 ? ("0" + minute) : minute) + " " + ((hourOfDay >= 12) ? "PM" : "AM")

output eg. 0:0 AM 12:00 PM 9:09 AM

thanks to @Lalit Jawale answer above


Here is the code to convert 24-Hour time to 12-Hour with AM and PM.
Note:- If you don't want AM/PM then just replace hh:mm a with hh:mm.

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
   public static void main(String [] args) throws Exception {
       try {       
           String _24HourTime = "22:15";
           SimpleDateFormat _24HourSDF = new SimpleDateFormat("HH:mm");
           SimpleDateFormat _12HourSDF = new SimpleDateFormat("hh:mm a");
           Date _24HourDt = _24HourSDF.parse(_24HourTime);
           System.out.println(_24HourDt);
           System.out.println(_12HourSDF.format(_24HourDt));
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

//OUTPUT WOULD BE
//Thu Jan 01 22:15:00 IST 1970
//10:15 PM

Another Solution:

System.out.println(hr%12 + ":" + min + " " + ((hr>=12) ? "PM" : "AM"));

In Java 8 it could be done in one line using class java.time.LocalTime.

Code example:

String result = LocalTime.parse(time, DateTimeFormatter.ofPattern("HH:mm")).format(DateTimeFormatter.ofPattern("hh:mm a"));

For earlier Android, use the ThreeTen-Backport project, adapted for Android in the ThreeTenABP project. See How to use ThreeTenABP in Android Project.


you can try using a SimpleDateFormat object to convert the time formats.

final String time = "23:15";

try {
    final SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
    final Date dateObj = sdf.parse(time);
    System.out.println(dateObj);
    System.out.println(new SimpleDateFormat("K:mm").format(dateObj));
} catch (final ParseException e) {
    e.printStackTrace();
}

here is the javadoc link for SimpleDateFromat.

Tags:

Java

Android