1. import java.time.LocalTime;
  2. import java.time.format.DateTimeFormatter;
  3. import java.time.format.DateTimeParseException;
  4. public class TimeMapper {
  5. /**
  6. * Maps a string time value to a LocalTime object.
  7. * @param timeString The string representation of the time (e.g., "14:30").
  8. * @param inputFormat The format of the input time string.
  9. * @param outputFormat The desired format of the output LocalTime.
  10. * @return A LocalTime object, or null if parsing fails.
  11. */
  12. public static LocalTime mapTime(String timeString, DateTimeFormatter inputFormat, DateTimeFormatter outputFormat) {
  13. try {
  14. // Parse the input time string
  15. LocalTime parsedTime = LocalTime.parse(timeString, inputFormat);
  16. // Format the LocalTime object to the desired output format
  17. return LocalTime.parse(outputFormat.format(parsedTime), outputFormat); //Re-parse to ensure correct formatting
  18. } catch (DateTimeParseException e) {
  19. // Handle parsing errors (e.g., invalid time string)
  20. return null;
  21. }
  22. }
  23. public static void main(String[] args) {
  24. // Example usage
  25. String timeString = "14:30";
  26. DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("HH:mm");
  27. DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("hh:mm a");
  28. LocalTime mappedTime = mapTime(timeString, inputFormat, outputFormat);
  29. if (mappedTime != null) {
  30. System.out.println("Original Time: " + timeString);
  31. System.out.println("Mapped Time: " + mappedTime);
  32. } else {
  33. System.out.println("Invalid time string format.");
  34. }
  35. }
  36. }

Add your comment