Question
Given a time in -hour AM/PM format, convert it to military (24-hour) time.
Note: Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
Sample Input
07:05:45PM
Sample Output
19:05:45
Solution
static String timeConversion(String s) { String time24 = null; int hour24 = 0; if (null == s || s.isBlank()) { return time24; } String[] arr = s.split(":"); String ampm = arr[2].substring(2, 4); boolean am = ampm.equalsIgnoreCase("AM"); if (arr.length > 0) { int hour = Integer.parseInt(arr[0]); if (hour == 12) { if (am) { hour24 = 0; } else { hour24 = hour; } } else if (hour < 12 && !am) { hour24 = hour + 12; } else { hour24 = hour; } if (hour24 < 10) { arr[0] = "0" + hour24; } else { arr[0] = String.valueOf(hour24); } } time24 = arr[0] + ":" + arr[1] + ":" + arr[2].substring(0, 2); return time24; }