Time Conversion

  • + 0 comments

    Java 8 based with 2 different approaches

        // Using Java LocalTime class.
        private static String timeConverterLocalTime(String input) {
            DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm:ssa");
            DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("HH:mm:ss");
            LocalTime timeIn24 = LocalTime.parse(input, timeFormatter);
            return timeIn24.format(outputFormat);
        }
    
        // Using Java algorithmic approach.
        private static String timeConverter(String input) {
            String timeIn24 = "";
            String hours = input.substring(0, 2);
            String timeWithoutPrefix = input.substring(0, input.length() - 2);
    
            if (input.contains("PM")) {
                if (hours.equals("12")) {
                    timeIn24 = timeWithoutPrefix;
                } else {
                    int hourIn24 = Integer.parseInt(hours) + 12;
                    timeIn24 = String.valueOf(hourIn24).concat(timeWithoutPrefix.substring(2));
                }
            }
    
            if (input.contains("AM")) {
                if (hours.equals("12")) {
                    timeIn24 = "00".concat(timeWithoutPrefix.substring(2));
                } else {
                    timeIn24 = timeWithoutPrefix;
                }
            }
            return timeIn24;
        }