Bootstrap

java 时间转换24小时制转换12小时制

public class Test4 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] tx = scanner.nextLine().split(":", 2);
        int hour = Integer.parseInt(tx[0]);
        int minute = Integer.parseInt(tx[1]);
        String flag;
        if (hour > 0 && hour < 12) {
            flag = "AM";
        } else if (hour == 24 || hour == 0) {
            hour = 12;
            flag = "AM";
        } else {
            flag = "PM";
            if(hour != 12) {
                hour %= 12;
            }
        }
        System.out.println(alignItem(hour) + ":" + alignItem(minute) + " " + flag);
    }
    public static String alignItem(int i) {
        return String.format("%02d", i);
    }
}

输入格式和结果:

 

;