Time Conversion

  • + 0 comments

    Java Solution

    Using a boolen value to indicate the time am/pm.

    public static String timeConversion(String s) {
        // Write your code here
            StringBuilder finalTime = new StringBuilder("");
            boolean isPm = false;
            for(int i = 0 ; i < s.length() ; i++){
                finalTime.append(s.charAt(i));
                int secoundLastEle  = s.length()-2;
                if(s.charAt(secoundLastEle) == 'A'){
                    isPm = false;
                }
                else {
                    isPm = true; 
                }
            }
            
            finalTime.deleteCharAt(finalTime.length()-1); // last deletecharAt 
            finalTime.deleteCharAt(finalTime.length()-1); // secound last deletecharAt 
            
                
                String subSet = finalTime.substring(0,2);
                int convert_time = Integer.parseInt(subSet);
                
                if(isPm){
                    if(convert_time != 12){
                        convert_time += 12;
                    }
                    String replace_convert_time = String.valueOf(convert_time);
                    finalTime.replace(0,2,replace_convert_time);
                }
                else{
                    if(subSet.equals("12")){
                        finalTime.replace(0,2,"00");
                    }
                }
            
            return finalTime.toString();
        }