Home > Back-end >  Common Method to map String DateTimes to Date, where DateTime is in different formats
Common Method to map String DateTimes to Date, where DateTime is in different formats

Time:03-01

I have three sources, which return timestamps as Strings in different formats. I need to turn these in to a Date only.

  • Format 1: "yyyy-MM-dd" Example: "2022-02-28"
  • Format 2: "yyyy-MM-dd'T'HH:mm:ss'Z'" Example: "2022-02-28T23:59:29Z"
  • Format 3: "yyyy-MM-dd'T'HH:mm:ss" Example: "20220228235929"

I was hoping to get a common method where I would pass the String in, and return the Date only.

I had tried using

Instant instant = Instant.parse(stringDate);
LocalDate date = LocalDateTime.ofInstant(instant, ZoneOffset.UTC).toDate();

But I have thought maybe I should have a range of List of Date Formats, and try using each one to parse the date?

List<SimpleDateFormat> dateFormats; // Read these formats from config file. 
        for(SimpleDateFormat format : dateFormats){
            try {               
                Date date = new SimpleDateFormat(format.toString()).parse(inputDate);
                return date;
            } catch(ParseException e) {
                log.info(e.getMessage());
            }
        }
        return null;

Additionally, once I've done some comparison of the Dates, I need to convert back to a String of the format "2022-02-28T23:59:59Z"

Any better approaches, as I've not worked with Java dates/timestamps before. Thanks!

CodePudding user response:

Never use SimpleDateFormat and Date classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

To parse all three possible formats, try successively to parse an input with each of the three formats. Trap for DateTimeParseException, trying one after another until one works or you run out of formats.

LocalDate.parse( "2022-02-28" )
Instant.parse( "2022-02-28T23:59:29Z" ) 
LocalDateTime.parse( "20220228235929" , DateTimeFormatter.ofPattern( "uuuuMMddHHmmss" ) )

Of course, each of those returns a different type of object.

CodePudding user response:

The approach I chose was:

        List<String> formats = Arrays.asList( //Read supported date formats from config);

        String msg = null;
        for(String format : formats) {
            try {
                LocalDate date = LocalDate.parse(dateTime, DateTimeFormatter.ofPattern(format)).atStartOfDay().toLocalDate();
                return date;
            } catch(DateTimeParseException e) { 
                msg = e.getMessage();
            }
        }
        // Unable to map timestamp to Date 
        log.error(msg);
        return null;
  • Related