Time Conversion

  • + 0 comments

    Java

    public static String timeConversion(String s) {
        // Extract the hour from the string
        int hour;
        if (s.charAt(2) == ':') {
            hour = Integer.parseInt(s.substring(0, 2)); // If there is a colon in the string, then the hour is extracted from the first two characters
        } else {
            hour = Integer.parseInt(s.substring(0, 1)); // Otherwise, the hour is extracted from the first character
        }
    
        // Check for AM/PM and convert the hour
        String result;
        int newHour;
        if (s.charAt(8) == 'P' || s.charAt(7) == 'P') { // If the string contains 'P', then it is PM
            newHour =  hour == 12 ? 12 : hour + 12; // If the hour is 12, then leave it as is, otherwise add 12
        } else {
            newHour =  hour == 12 ? 0 : hour; // If it's not PM and the hour is 12, then set it to 0, otherwise leave it as is
        }
    
        result = "%02d:%s".formatted(
                newHour,
                s.charAt(2) == ':' ? s.substring(3, s.length() - 2) : s.substring(2, s.length() - 2)
        ); // Format the result by adding leading zeros to the hour and returning the remaining part of the string after extracting the hour
    
        return result;
    }