convert a 4-digit military time into the standard 12 hour time format

前端 未结 4 1998
半阙折子戏
半阙折子戏 2020-12-18 03:53

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

4条回答
  •  囚心锁ツ
    2020-12-18 04:28

    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;
    }
    

提交回复
热议问题