基于Chris Nava的想法(首先回答他的回答)并假设您想要int数字而不是char:
public class TimeSplit {
public static void main(String[] args) throws ParseException {
printSplit("8:24"); // [0, 8, 2, 4]
printSplit("10:22"); // [1, 0, 2, 2]
printSplit("13:57"); // [0, 1, 5, 7] because of 12h
}
private static void printSplit(String time) throws ParseException {
System.out.println(time + " -> " + Arrays.toString(split(time)));
}
private static int[] split(String time) throws ParseException {
DateFormat fmt = new SimpleDateFormat("hh:mm"); // 12h, use HH for 24h
Calendar calendar = Calendar.getInstance();
calendar.setTime(fmt.parse(time));
return split(calendar);
}
private static int[] split(Calendar time) {
int hours = time.get(Calendar.HOUR); // 12h, use HOUR_OF_DAY for 24h
int minutes = time.get(Calendar.MINUTE);
int[] digits = new int[4];
digits[0] = hours / 10;
digits[1] = hours % 10;
digits[2] = minutes / 10;
digits[3] = minutes % 10;
return digits;
}
}输出:
8:24 -> [0, 8, 2, 4]
10:22 -> [1, 0, 2, 2]
13:57 -> [0, 1, 5, 7]