Time Conversion

  • + 0 comments

    public static String timeConversion(String s) { int n = s.length(); String period = s.substring(n - 2); // Extract AM or PM int hour = Integer.parseInt(s.substring(0, 2)); // Extract hour part String minAndSec = s.substring(2, n - 2); // Extract minutes and seconds

        // Convert the hour based on the period (AM/PM)
        if (period.equals("AM")) {
            if (hour == 12) {
                hour = 0;  // Midnight case: 12 AM -> 00 in 24-hour format
            }
        } else {
            if (hour != 12) {
                hour += 12;  // Afternoon/evening case: convert PM hour to 24-hour format
            }
        }
    
        // Format and return the converted time
        return String.format("%02d%s", hour, minAndSec);
    }
    

    }