Convert 24 hours to 12 hours?

Hello, I am using an Android app and I am trying to figure out how to convert a 24-hour time to 12 hours.

Example 24 hour format 12:18:00 to 12 hour format 12:18pm 
+4
source share
6 answers

Try using 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" 
+14
source

If you are using Java 8 or 9, you can use the java.time library as follows:

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

Output

 10:18PM 
+2
source

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

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

  SimpleDateFormat sdf=new SimpleDateFormat("h:mm a"); sdf.format(dateObject); 
0
source

Use SimpleDateFormat, but note that HH is different from hh.

Say we have time 18:20

The format below will return 18:20

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

Until this format returns 6:20 pm

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

Hope this helps ...

0
source
 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(); } 
0
source

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(); } 
-1
source

Source: https://habr.com/ru/post/1380601/


All Articles