Converting 24hour time to 12hour time?

21,607

Solution 1

Try using a SimpleDateFormat:

String s = "12:18:00";
DateFormat f1 = new SimpleDateFormat("HH:mm:ss"); //HH for hour of the day (0 - 23)
Date d = f1.parse(s);
DateFormat f2 = new SimpleDateFormat("h:mma");
f2.format(d).toLowerCase(); // "12:18am"

Solution 2

If you are using Java 8 or 9 you can use java.time library like this :

String time = "22:18:00";
String result = LocalTime.parse(time).format(DateTimeFormatter.ofPattern("h:mma"));

Output

10:18PM
Share:
21,607
ericlee
Author by

ericlee

Updated on March 17, 2020

Comments

  • ericlee
    ericlee over 4 years

    Hello I am using an android application and I am trying to figure out how to convert a 24 hour time to a 12hour time.

    Example 
    24 hour format 12:18:00
    
    to 
    12 hour format 12:18pm