What I\'m trying to do:
I\'m trying to convert a 4-digit military time into the standard 12 hour time format, with a colon and an added PM or AM wit
Your problem is screaming out that you should be using your own custom data formatter. I like using the Joda Time library and its DateTime class instead of the built-in Java Date and Calendar classes. Therefore, instead of SimpleDateFormat, I recommend that you use a DateTimeFormat to create a DateTimeFormatter, which you will then use to convert your String into a DateTime. You will need one DateTimeFormatter for each of input and output. For example:
String rawTimestamp = "2300"; // For example
DateTimeFormatter inputFormatter = DateTimeFormat.forPattern("HHmm");
DateTimeFormatter outputFormatter = DateTimeFormat.forPattern("hh:mm a");
DateTime dateTime = inputFormatter.parseDateTime(rawTimestamp);
String formattedTimestamp = outputFormatter.print(dateTime.getMillis());
return formattedTimestamp;
Try this out!
public static String convert24HourToAmPm(String time) {
if (time == null)
return time;
// Convert time where time is like: 0100, 0200, 0300....2300...
if (time.length() == 4 && Helper.isInteger(time)) {
String hour = time.substring(0,2);
String minutes = time.substring(2,4);
String meridian = "am";
if (hour.substring(0,2).equals("00")) {
hour = "12";
} else if (hour.substring(0,1).equals("1") || hour.substring(0,1).equals("2")) {
meridian = "pm";
Integer militaryHour = Integer.parseInt(hour);
Integer convertedHour = null;
if (militaryHour > 12) {
convertedHour = (militaryHour - 12);
if (convertedHour < 10)
hour = "0" + String.valueOf(convertedHour);
else
hour = String.valueOf(convertedHour);
}
}
time = hour + ":" + minutes + " " + meridian;
}
// TODO - Convert time where time is like 01:00...23:00...
return time;
}
You can do this much, much simpler, using a clever string conversion and SimpleDateFormat, here is the example but parsed in two lines:
// Heres your military time int like in your code sample
int milTime = 56;
// Convert the int to a string ensuring its 4 characters wide, parse as a date
Date date = new SimpleDateFormat("hhmm").parse(String.format("%04d", milTime));
// Set format: print the hours and minutes of the date, with AM or PM at the end
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
// Print the date!
System.out.println(sdf.format(date));
// Output: 12:56 AM
if (pm = true)
if (pm = false)
A single equal sign is an assignment. You want to do a comparison:
if (pm == true)
if (pm == false)
These could also be written more idiomatically as:
if (pm)
if (!pm)
That's the main problem. Another is your logic for setting pm
. You only need a single if
statement, with the line subtracting 1200 placed inside the pm = true
block.
if (milTime < 1200)
{
pm = false;
}
else
{
pm = true;
milTime -= 1200;
}
There are a few other bugs that I'll leave to you. I trust these corrections will get you a bit further, at least.