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

Viewed 93744

In my application i want to convert the given CDT formatted 24 hr string in to CDT formatted 12 hr string, How to convert a given 24 hr format string in to 12 hr format string??

16 Answers

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

// time is your string value i.e., 24 hour time

    try {
    final SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                final Date dateObj = sdf.parse(time);
                time = new SimpleDateFormat("hh:mm aa").format(dateObj);
            } catch (final ParseException e) {
                e.printStackTrace();
            }

SimpleDateFormat with (K:mm) works fine, but won't work properly with time 12:00 AM or 12:00 PM

You can use the above code to convert 12 hour format from 24 hour format along with AM/PM... It works

in a clean way you can do this:

fun convertTo12Hours(militaryTime: String): String{
        //in => "14:00:00"
        //out => "02:00 PM"
        val inputFormat = SimpleDateFormat("hh:mm:ss", Locale.getDefault())
        val outputFormat = SimpleDateFormat("hh:mm aa", Locale.getDefault())
        val date = inputFormat.parse(militaryTime)
        return outputFormat.format(date)
    }

I don't like using classes like SimpleDateFormat if it's not necessary. You just have to check three conditions. Here are some alternatives:

Simple:

if(hour>11) {
    suffix = "PM";
    if(hour>12)
        hour -= 12;
} else {
    suffix = "AM";
    if(hour==0)
        hour = 12;
}

Short:

suffix = (hour>11) ? "PM" : "AM";
hour = (hour>12) ? hour-=12 : ((hour==0) ? 12 : hour);

Result:

00:00 = 12:00 AM, 01:00 = 01:00 AM, 02:00 = 02:00 AM, 03:00 = 03:00 AM, 04:00 = 04:00 AM, 05:00 = 05:00 AM, 06:00 = 06:00 AM, 07:00 = 07:00 AM, 08:00 = 08:00 AM, 09:00 = 09:00 AM, 10:00 = 10:00 AM, 11:00 = 11:00 AM, 12:00 = 12:00 PM, 13:00 = 01:00 PM, 14:00 = 02:00 PM, 15:00 = 03:00 PM, 16:00 = 04:00 PM, 17:00 = 05:00 PM, 18:00 = 06:00 PM, 19:00 = 07:00 PM, 20:00 = 08:00 PM, 21:00 = 09:00 PM, 22:00 = 10:00 PM, 23:00 = 11:00 PM

Follow below code:

Make common method and call from where you need:

COMMON METHOD TO CHANGE TIME:

  public static String parseTime(String date, String inFormat, String outFormat) {
        try {
            Date date1 = new SimpleDateFormat(inFormat, Locale.getDefault()).parse(date);
            SimpleDateFormat dateFormat = new SimpleDateFormat(outFormat, Locale.getDefault());
            return dateFormat.format(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

CONSTANT METHOD:

public static final String SERVER_TIME_RESOURCES_FORMAT = "HH:mm:ss";
    public static final String SERVER_TIME_FORMAT = "HH:mm:ss.SSS";

CALL FROM WHER U NEED:

CommonMethods.parseTime(//your date, Constants.SERVER_TIME_RESOURCES_FORMAT, Constants.LOCAL_TIME_FORMAT);

Here I use simple maths. 12Hours = 1 + currentHours(24Hours)-13. For AM & PM use simple ifelse condition, like if currentHours(24Hours) is <= 12 then set 'AM' or set 'PM' Here AMPM & Time is String varriable. CurHour is int.

LocalDateTime LDT = LocalDateTime.now();
        CurHour = LDT.getHour();
        if(CurHour <=12) {
            AMPM = "AM";
        }else {
            AMPM = "PM";
        }
        Hours = 1+CurHour-13;
        Time = Hours+":"+LDT.getMinute()+":"+LDT.getSecond()+" "+AMPM;

Here's my solution:

/*
* hour in 24Format -> AM/PM Format
*/
public String format(int hour, int minutes ){

   String meridiem = hour > 11 ? "PM" : "AM";

   // trim "0-23 hour" to "0-11 hour", then replace "0" with "12" 
   hour = (hour %= 12) == 0 ? 12 : hour;

   // Apply desired format "HH:MM AM/PM"
   return String.format("%02d:%02d %s", hour, minutes, meridiem );
}
public static void convert24HourTimeInto12Hour() {
try {      
    String[] dateTime = getCurrentDateAndTime("yyyy-MM-dd HH:mm:ss").split(" ");                  
    System.out.println("datePart::: "+dateTime[0]);         
    System.out.println("timePart::: "+dateTime[1]);         

    SimpleDateFormat 24HoursFormat = new SimpleDateFormat
    SimpleDateFormat 12HoursFormat = new SimpleDateFormat
    Date 24Hours = 24HoursFormat.parse(dateTime[1]);      
    System.out.println(24Hours);                  
    System.out.println(12HoursFormat.format(24Hours)); 
    } catch (Exception e) {           
        e.printStackTrace();          
    }         
}                       

For converting any Date date to 12 hour format with AM and PM you can use

new SimpleDateFormat("dd MMM yyyy KK:mm:ss a").format(date)

Here KK signifies 00-12 and a signifies AM and PM

This is what I have used, it converts 00:10 am to 12:00 am and the remaining also works fine.

int hourOfDay=Integer.parseInt(form24hrs);//parsing 24 hours format string value of hour to int

int minute=Integer.parseInt(form24min);//parsing 24 hours format string value of minute to int

String time =  ((hourOfDay > 12) ? hourOfDay % 12 : ((hourOfDay==0)?"12":hourOfDay)) + ":" + (minute < 10 ? ("0" + minute) : minute) + " " + ((hourOfDay >= 12) ? "pm" : "am");

Kotlin version of @xianwei 's answer

  val hourOfDay = timePicker.hour
  val minute = timePicker.minute
  val finalHour = (if (hourOfDay > 12) hourOfDay % 12 else hourOfDay).toString()
  val finalMinute = if (minute < 10) "0$minute" else minute.toString()
  val finalMeridian = if (hourOfDay > 12) "PM" else "AM"
  val time = "$finalHour:$finalMinute $finalMeridian"
Related