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
YCF_L
  • 51,266
  • 13
  • 85
  • 129
ericlee
  • 2,654
  • 10
  • 41
  • 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,207
  • 14
  • 28
maerics
  • 143,080
  • 41
  • 260
  • 285
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
YCF_L
  • 51,266
  • 13
  • 85
  • 129
  • 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 – YCF_L 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,048
  • 19
  • 36
  • 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
  • 843
  • 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
  • 70,421
  • 14
  • 74
  • 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,465
  • 1
  • 28
  • 40