`import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class TimeParserTest {
public static void main(String[] args) {
DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");
String[] testTimes = {"01:30 PM", "02:20 PM", "07:00 PM", "08:50 PM", "11:30 AM"};
for (String timeStr : testTimes) {
String originalTimeStr = timeStr; // Keep the original for reference
timeStr = timeStr.trim().toUpperCase(); // Ensure no leading/trailing spaces and uppercase AM/PM
System.out.println("Original: '" + originalTimeStr + "', Parsing: '" + timeStr + "'"); // Debugging line
try {
LocalTime time = LocalTime.parse(timeStr, timeFormatter);
System.out.println("Parsed time: " + time);
} catch (DateTimeParseException e) {
System.err.println("Failed to parse time: '" + timeStr + "' from original: '" + originalTimeStr + "'");
}
}
}
}
`
I have a file way bigger than this text file that I need to parse the time from a string. It wasn’t working so I made this test to see if it was a formatting issue but this doesn’t work either.
New contributor
Charles Rachwal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.