import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class TimeMapper {
/**
* Maps a string time value to a LocalTime object.
* @param timeString The string representation of the time (e.g., "14:30").
* @param inputFormat The format of the input time string.
* @param outputFormat The desired format of the output LocalTime.
* @return A LocalTime object, or null if parsing fails.
*/
public static LocalTime mapTime(String timeString, DateTimeFormatter inputFormat, DateTimeFormatter outputFormat) {
try {
// Parse the input time string
LocalTime parsedTime = LocalTime.parse(timeString, inputFormat);
// Format the LocalTime object to the desired output format
return LocalTime.parse(outputFormat.format(parsedTime), outputFormat); //Re-parse to ensure correct formatting
} catch (DateTimeParseException e) {
// Handle parsing errors (e.g., invalid time string)
return null;
}
}
public static void main(String[] args) {
// Example usage
String timeString = "14:30";
DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("HH:mm");
DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("hh:mm a");
LocalTime mappedTime = mapTime(timeString, inputFormat, outputFormat);
if (mappedTime != null) {
System.out.println("Original Time: " + timeString);
System.out.println("Mapped Time: " + mappedTime);
} else {
System.out.println("Invalid time string format.");
}
}
}
Add your comment