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
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
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"
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
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...
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();
}
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);
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();
}