5

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
ericlee
  • 2,703
  • 11
  • 43
  • 68

6 Answers6

15

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"
Yedhu Krishnan
  • 1,225
  • 15
  • 31
maerics
  • 151,642
  • 46
  • 269
  • 291
3

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 2
    This is the modern way and the recommended one in 2018. On not-brand-new Android it works too when you add ThreeTenABP to your Android project and make sure you import the date-time classes from `org.threeten.bp` with subpackages. See [this question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Mar 16 '18 at 20:09
  • Thank you @OleV.V. happy to hear all this information, always learn from you – Youcef LAIDANI Mar 16 '18 at 20:12
0

Use SimpleDateFormat but note that HH is different from hh.

Say we have a time of 18:20

The format below would return 18:20 PM

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm aa");

While this format would return 6:20 PM

SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");

Hope this helps...

Ankur
  • 5,086
  • 19
  • 37
  • 62
Philip
  • 503
  • 7
  • 8
0
final String timein24Format = "22:10";

try {
    final SimpleDateFormat sdf = new SimpleDateFormat("H:mm");
    final Date dateObj = sdf.parse(timein24Format );
    String timein12Format=new SimpleDateFormat("K:mm a").format(dateObj));
} catch (final ParseException e) {
    e.printStackTrace();
}
Jasmine John
  • 873
  • 8
  • 12
0

You'll most likely need to take a look at Java SimpleDateFormat.

To display the data in the format you want you should use something like this:

   SimpleDateFormat sdf=new SimpleDateFormat("h:mm a");
   sdf.format(dateObject);
Ovidiu Latcu
  • 71,607
  • 15
  • 76
  • 84
-1

try this code

     String s= time ;

     DateFormat f1 = new SimpleDateFormat("kk:mm");
     Date d = null;
        try {
             d = f1.parse(s);
             DateFormat f2 = new SimpleDateFormat("h:mma");
             time = f2.format(d).toUpperCase(); // "12:18am"

    } catch (ParseException e) {

        // TODO Auto-generated catch block
            e.printStackTrace();
        }
Nithinlal
  • 4,845
  • 1
  • 29
  • 40