import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class TimeFallback {
public static LocalDateTime getLocalDateTime(String timeString, ZoneId zoneId, boolean dryRun) {
try {
//Attempt to parse the time string with the specified formatter and zone.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //Adjust pattern as needed
LocalDateTime dateTime = LocalDateTime.parse(timeString, formatter);
return dateTime;
} catch (Exception e) {
// Fallback if parsing fails.
if (dryRun) {
System.err.println("Dry Run: Time parsing failed for " + timeString + ". Using fallback.");
return LocalDateTime.now(); //Return current time for dry-run
} else {
System.err.println("Time parsing failed for " + timeString + ". Returning current time as fallback.");
return LocalDateTime.now(); //Return current time as fallback in production.
}
}
}
public static Date getDate(String dateString, boolean dryRun) {
try {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Adjust pattern as needed
Date date = Date.from(LocalDateTime.parse(dateString, formatter).atZone(ZoneId.systemDefault()).toInstant());
return date;
} catch (Exception e) {
if (dryRun) {
System.err.println("Dry Run: Date parsing failed for " + dateString + ". Using fallback.");
return new Date(); //Return current date for dry-run
} else {
System.err.println("Date parsing failed for " + dateString + ". Returning current date as fallback.");
return new Date(); //Return current date as fallback in production.
}
}
}
public static void main(String[] args) {
//Example Usage
String timeString = "2024-01-27 10:30:00";
ZoneId zoneId = ZoneId.of("America/Los_Angeles");
boolean dryRun = true; // Set to false for production
LocalDateTime localDateTime = getLocalDateTime(timeString, zoneId, dryRun);
System.out.println("Local Date and Time: " + localDateTime);
String dateString = "2024-02-29";
Date date = getDate(dateString, dryRun);
System.out.println("Date: " + date);
}
}
Add your comment