import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
class TimeValidator {
/**
* Validates a time string, handling potential errors and ensuring backward compatibility.
* @param timeString The time string to validate.
* @param expectedFormat The expected format of the time string.
* @return A LocalTime object if the time string is valid, otherwise null.
*/
public static LocalTime validateTime(String timeString, String expectedFormat) {
try {
// Use DateTimeFormatter to parse the time string.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(expectedFormat);
LocalTime time = LocalTime.parse(timeString, formatter);
return time;
} catch (DateTimeParseException e) {
// Handle parsing errors (invalid time format).
System.err.println("Error: Invalid time format. Expected: " + expectedFormat + ", Actual: " + timeString);
return null;
} catch (NullPointerException e) {
// Handle null input.
System.err.println("Error: Time string cannot be null.");
return null;
}
}
/**
* Validates a date and time string, handling potential errors and ensuring backward compatibility.
* @param dateTimeString The date and time string to validate.
* @param expectedFormat The expected format of the date and time string.
* @return A LocalDate object if the date and time string is valid, otherwise null.
*/
public static LocalDate validateDateTime(String dateTimeString, String expectedFormat) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(expectedFormat);
LocalDate date = LocalDate.parse(dateTimeString, formatter);
return date;
} catch (DateTimeParseException e) {
System.err.println("Error: Invalid date/time format. Expected: " + expectedFormat + ", Actual: " + dateTimeString);
return null;
} catch (NullPointerException e) {
System.err.println("Error: Date/time string cannot be null.");
return null;
}
}
public static void main(String[] args) {
// Example Usage
String timeStr1 = "14:30";
String timeStr2 = "invalid_time";
String dateTimeStr1 = "2024-01-01 14:30";
String dateTimeStr2 = "invalid date";
String dateTimeStr3 = null;
LocalTime time1 = validateTime(timeStr1, "HH:mm");
LocalTime time2 = validateTime(timeStr2, "HH:mm");
LocalDate date1 = validateDateTime(dateTimeStr1, "yyyy-MM-dd HH:mm");
LocalDate date2 = validateDateTime(dateTimeStr2, "yyyy-MM-dd HH:mm");
LocalDate date3 = validateDateTime(dateTimeStr3, "yyyy-MM-dd HH:mm");
if (time1 != null) {
System.out.println("Valid Time: " + time1);
}
if (time2 == null) {
System.out.println("Invalid Time: " + time2);
}
if (date1 != null) {
System.out.println("Valid Date: " + date1);
}
if (date2 == null) {
System.out.println("Invalid Date: " + date2);
}
if(date3 == null) {
System.out.println("Invalid Date: " + date3);
}
}
}
Add your comment