You're working too hard.
Parsing is easier using a regular expression.
Figuring out the mirrored time is easier if you convert everything into minutes first.
Formatting the output is easier using String.format()
.
private static final Pattern TIME_FMT = Pattern.compile("(0?[1-9]|1[0-2]):([0-5]\\d)\\s*([ap]m)", Pattern.CASE_INSENSITIVE);
private static final int MINUTES_PER_HALF_DAY = 12 * 60;
public static String parallelUniverseTime(String time) {
Matcher m = TIME_FMT.matcher(time);
if (!m.matches()) {
return null;
}
int hour = Integer.parseInt(m.group(1)) % 12;
int minute = Integer.parseInt(m.group(2));
String ampm = m.group(3).toLowerCase();
int minutes = 60 * hour + minute;
// ^^^ Normal universe ^^^
// ** WARP! **
// vvv Parallel universe vvv
minutes = MINUTES_PER_HALF_DAY - minutes;
hour = minutes / 60;
if (hour == 0) {
hour = 12;
}
minute = minutes % 60;
ampm = ("pm".equals(ampm)) ? "am" : "pm";
return String.format("%02d:%02d %s", hour, minute, ampm);
}