How to convert 24 hr format time in to 12 hr Format?
Solution 1:
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"));
Solution 2:
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.
Solution 3:
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.
Solution 4:
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