1. import java.time.LocalDateTime;
  2. import java.time.ZoneId;
  3. import java.time.format.DateTimeFormatter;
  4. import java.util.Date;
  5. public class TimeFallback {
  6. public static LocalDateTime getLocalDateTime(String timeString, ZoneId zoneId, boolean dryRun) {
  7. try {
  8. //Attempt to parse the time string with the specified formatter and zone.
  9. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); //Adjust pattern as needed
  10. LocalDateTime dateTime = LocalDateTime.parse(timeString, formatter);
  11. return dateTime;
  12. } catch (Exception e) {
  13. // Fallback if parsing fails.
  14. if (dryRun) {
  15. System.err.println("Dry Run: Time parsing failed for " + timeString + ". Using fallback.");
  16. return LocalDateTime.now(); //Return current time for dry-run
  17. } else {
  18. System.err.println("Time parsing failed for " + timeString + ". Returning current time as fallback.");
  19. return LocalDateTime.now(); //Return current time as fallback in production.
  20. }
  21. }
  22. }
  23. public static Date getDate(String dateString, boolean dryRun) {
  24. try {
  25. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Adjust pattern as needed
  26. Date date = Date.from(LocalDateTime.parse(dateString, formatter).atZone(ZoneId.systemDefault()).toInstant());
  27. return date;
  28. } catch (Exception e) {
  29. if (dryRun) {
  30. System.err.println("Dry Run: Date parsing failed for " + dateString + ". Using fallback.");
  31. return new Date(); //Return current date for dry-run
  32. } else {
  33. System.err.println("Date parsing failed for " + dateString + ". Returning current date as fallback.");
  34. return new Date(); //Return current date as fallback in production.
  35. }
  36. }
  37. }
  38. public static void main(String[] args) {
  39. //Example Usage
  40. String timeString = "2024-01-27 10:30:00";
  41. ZoneId zoneId = ZoneId.of("America/Los_Angeles");
  42. boolean dryRun = true; // Set to false for production
  43. LocalDateTime localDateTime = getLocalDateTime(timeString, zoneId, dryRun);
  44. System.out.println("Local Date and Time: " + localDateTime);
  45. String dateString = "2024-02-29";
  46. Date date = getDate(dateString, dryRun);
  47. System.out.println("Date: " + date);
  48. }
  49. }

Add your comment