Converting 12-Hour Time to 24-Hour Time in Java on HackerRank

Converting time from the 12 - hour format (e.g., 03:45:23 PM) to the 24 - hour format (e.g., 15:45:23) is a common programming problem, and HackerRank often presents it as a challenge. This conversion is not only useful for solving coding problems but also has real - world applications in scheduling systems, international time representation, and data processing. In this blog post, we will explore how to solve this problem in Java, covering core concepts, usage scenarios, common pitfalls, and best practices.

Table of Contents

  1. Core Concepts
  2. Typical Usage Scenarios
  3. Java Code Example
  4. Common Pitfalls
  5. Best Practices
  6. Conclusion
  7. FAQ
  8. References

Core Concepts

12 - Hour and 24 - Hour Time Formats

  • 12 - Hour Format: This format divides the day into two 12 - hour periods: AM (ante meridiem, before noon) and PM (post meridiem, after noon). For example, 1:00 AM represents 1 o’clock in the morning, and 1:00 PM represents 1 o’clock in the afternoon.
  • 24 - Hour Format: In this format, the day is divided into 24 hours, starting from 00:00 (midnight) and ending at 23:59. For example, 1:00 AM is represented as 01:00, and 1:00 PM is represented as 13:00.

String Manipulation in Java

To convert the 12 - hour time to 24 - hour time, we need to perform string manipulation in Java. We will extract the hour, minute, second, and AM/PM indicator from the input string and then convert the hour based on the AM/PM indicator.

Typical Usage Scenarios

  • Scheduling Systems: Many scheduling applications use the 24 - hour format for clarity and to avoid confusion between AM and PM. When users enter time in the 12 - hour format, the application needs to convert it to the 24 - hour format for internal processing.
  • International Time Representation: Different countries use different time formats. When presenting time to an international audience, it is often better to use the 24 - hour format. Converting from the 12 - hour format to the 24 - hour format can help in providing a consistent time representation.
  • Data Processing: When dealing with time - related data from different sources, some data may be in the 12 - hour format, and others may be in the 24 - hour format. Converting all the data to the same format simplifies the data processing.

Java Code Example

import java.util.Scanner;

public class TimeConversion {
    public static String timeConversion(String s) {
        // Extract the AM/PM indicator
        String amPm = s.substring(8);
        // Extract the hour, minute, and second
        String timePart = s.substring(0, 8);
        String[] parts = timePart.split(":");
        int hour = Integer.parseInt(parts[0]);
        int minute = Integer.parseInt(parts[1]);
        int second = Integer.parseInt(parts[2]);

        if (amPm.equals("PM") && hour != 12) {
            // If it is PM and not 12 PM, add 12 to the hour
            hour += 12;
        } else if (amPm.equals("AM") && hour == 12) {
            // If it is AM and 12 AM, set the hour to 0
            hour = 0;
        }

        // Format the hour, minute, and second to have two digits
        String formattedHour = String.format("%02d", hour);
        String formattedMinute = String.format("%02d", minute);
        String formattedSecond = String.format("%02d", second);

        return formattedHour + ":" + formattedMinute + ":" + formattedSecond;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        String result = timeConversion(s);
        System.out.println(result);
        scanner.close();
    }
}

Code Explanation

  1. timeConversion Method:
    • First, we extract the AM/PM indicator from the input string using substring(8).
    • Then, we extract the hour, minute, and second part of the time using substring(0, 8) and split it using the split method.
    • We convert the hour, minute, and second strings to integers.
    • Based on the AM/PM indicator, we adjust the hour value.
    • Finally, we format the hour, minute, and second to have two digits using String.format("%02d", ...) and return the converted time.
  2. main Method:
    • We create a Scanner object to read the input from the user.
    • We call the timeConversion method with the input string and print the result.

Common Pitfalls

  • Handling 12 AM and 12 PM: Special care must be taken when handling 12 AM and 12 PM. 12 AM should be converted to 00:00, and 12 PM should remain 12:00.
  • Input Validation: The code assumes that the input string is in the correct 12 - hour format (e.g., hh:mm:ssAM or hh:mm:ssPM). If the input is not in the correct format, the code may throw a NumberFormatException or produce incorrect results.
  • String Manipulation Errors: Incorrect use of substring and split methods can lead to incorrect extraction of the hour, minute, second, and AM/PM indicator.

Best Practices

  • Input Validation: Add input validation to ensure that the input string is in the correct 12 - hour format. You can use regular expressions to validate the input.
  • Use Java’s Date and Time API: Java 8 introduced the java.time package, which provides a more robust and flexible way to handle date and time. You can use the DateTimeFormatter class to parse and format time in different formats.
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TimeConversionBestPractice {
    public static String timeConversionBestPractice(String s) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("hh:mm:ssa");
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        LocalTime time = LocalTime.parse(s, inputFormatter);
        return time.format(outputFormatter);
    }

    public static void main(String[] args) {
        String s = "03:45:23PM";
        String result = timeConversionBestPractice(s);
        System.out.println(result);
    }
}

Conclusion

Converting 12 - hour time to 24 - hour time in Java is a fundamental problem that requires an understanding of string manipulation and time format conversion. By following the best practices and avoiding common pitfalls, you can write robust and efficient code to solve this problem. Whether you are solving a HackerRank challenge or working on a real - world application, this knowledge will be valuable.

FAQ

Q1: Why is the 24 - hour format preferred in some applications?

A1: The 24 - hour format is preferred because it is more precise and eliminates the confusion between AM and PM. It is also widely used in international contexts and in scheduling systems.

Q2: What if the input string is not in the correct 12 - hour format?

A2: If the input string is not in the correct format, the code may throw a NumberFormatException or produce incorrect results. You can add input validation using regular expressions to handle such cases.

Q3: Can I use the java.util.Date class to solve this problem?

A3: While you can use the java.util.Date class, it is recommended to use the java.time package introduced in Java 8, as it provides a more modern and user - friendly API for handling date and time.

References