convert a string of time to 24 hour format
datetime, java, substring
Solution
Working code (considering that you managed to split the Strings):
public class App {
public static void main(String[] args) {
try {
System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
System.out.println(convertTo24HoursFormat("9:30PM")); // 21:30
} catch (ParseException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Replace with KK:mma if you want 0-11 interval
private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
// Replace with kk:mm if you want 1-24 interval
private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");
public static String convertTo24HoursFormat(String twelveHourTime)
throws ParseException {
return TWENTY_FOUR_TF.format(
TWELVE_TF.parse(twelveHourTime));
}
}
Now that I think about it, SimpleDateFormat, `H h K k` can be confusing.
Cheers.
Problem
I have a `string` holding a start time and an end time in this format `8:30AM - 9:30PM` I want to be able to strip out the `AM -` and the `PM` and convert all the times to 24 hour format so `9:30PM` would really be `21:30` and also have both the times stored in 2 different variables, I know how to strip the string into `substrings` but Im not sure about the conversion, this is what I have so far. the time variable starts out holding `8:30AM - 9:30PM`. ``` String time = strLine.substring(85, 110).trim(); //time is "8:30AM - 9:30PM" String startTime; startTime = time.substring(0, 7).trim(); //startTime is "8:30AM" String endTime; endTime = time.substring(9).trim(); //endTime "9:30AM" ```