52

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??

SMR
  • 6,628
  • 2
  • 35
  • 56
ram
  • 3,487
  • 10
  • 33
  • 47

17 Answers17

86

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"));
Lalit Jawale
  • 1,216
  • 9
  • 19
  • 6
    Won't the "other solution" print '0' for midnight and noon? You'd have to have a special case for those. – Mark Sholund Oct 17 '14 at 12:16
  • `System.out.println(((hourOfDay%12==0) ? "12" : String.valueOf(hourOfDay%12)) + ":" + (minute>9 ? minute : "0"+minute) + " " +((hourOfDay>=12) ? "PM" : "AM"))` handles all cases – Darshan Soni Oct 12 '18 at 05:29
  • `System.out.println((((hourOfDay % 12 == 0) ? "12" : ((hourOfDay % 12) > 9 ? (hourOfDay % 12) : "0" + (hourOfDay % 12))) + ":" + ((minute > 9) ? minute : ("0" + minute)) + " " + ((hourOfDay >= 12) ? "PM" : "AM")));` – Renish Patel Dec 07 '18 at 07:20
65

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.

Anantha Sharma
  • 9,920
  • 4
  • 33
  • 35
17

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.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Cloud
  • 983
  • 11
  • 11
  • 1
    Here we need to pass minute value is always two digits.For example for 3 PM - 15:00 – Ajay Prajapati Sep 19 '20 at 15:22
  • I found this enough: `String result = localTimeInstance.format(DateTimeFormatter.ofPattern("hh:mm a"));` – Saleh Rezq Dec 16 '21 at 16:31
  • Saleh Rezq, yes, this is enough when you have time represented as a LocalTime initially. But if you have time represented as a String, then you need to use LocalTime.parse first. – Cloud Dec 18 '21 at 07:59
6

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

Xianwei
  • 2,381
  • 2
  • 22
  • 26
4

In case you are curious about the difference between K, k and H, h:

H Hour in day (0-23) Number 0 1+

k Hour in day (1-24) Number 24 1+

K Hour in am/pm (0-11) Number 0 1+

h Hour in am/pm (1-12) Number 12 1+

Kai Wang
  • 3,303
  • 1
  • 31
  • 27
3
// 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

2

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
einUsername
  • 1,569
  • 2
  • 15
  • 26
2

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)
    }
Asad
  • 1,241
  • 3
  • 19
  • 32
1
int n=2;
int result= n-12;

if (result>o) {
    system.out.println(result+"pm");
} else {
    system.out.prinln(result+"am");
} 

You can use Scanner if you want take input from user Hope this is simple 12 for time :)

tuomastik
  • 4,559
  • 5
  • 36
  • 48
punkaj rwt
  • 11
  • 1
0

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);
Rohan Lodhi
  • 1,385
  • 9
  • 24
0

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;
0

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 );
}
carlos ezam
  • 71
  • 1
  • 6
0
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();          
    }         
}                       
0

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

Arun
  • 785
  • 8
  • 13
0

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");
metvsk
  • 189
  • 2
  • 4
0

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"
Fayaz
  • 1,846
  • 2
  • 16
  • 21
0
 public static String convertYourTime(String time24) {
        try {
            SimpleDateFormat format24 = new SimpleDateFormat("HH:mm");
            Date time = format24.parse(time24);
            SimpleDateFormat format12 = new SimpleDateFormat("hh:mm a");
            return format12.format(time);
        } catch (ParseException e) {
            // Handle invalid input
          
        }

    }

Abdul Basit
  • 131
  • 7