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

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"));

Leave a Comment