Home > OS >  Convert ISO vs Date in Java. With code example
Convert ISO vs Date in Java. With code example

Time:05-27

I need to create a method received the date in two formats:

  • 2022-05-27T17:38:00.000Z (with time ISO)

  • 2022-05-27 (basic date)

My code:

 private static final String DATE_TIME_FORMAT = "dd-MM-yyyy HH:mm";


 private String getFormattedDateTime(String date){
    DateTimeFormatter formatter = DateTimeFormatter
            .ofPattern(DATE_TIME_FORMAT).withZone(ZoneId.of("UTC"));
    Instant instant = DateTimeFormatter.ISO_INSTANT.parse(date, Instant::from);
    return formatter.format(instant);
}

Throws exception on the simple date format:

java.time.format.DateTimeParseException: Text '2022-05-27' could not be parsed at index 10 at java.base/java.time.format.DateTimeFormatter.parseResolved0(Unknown Source) at java.base/java.time.format.DateTimeFormatter.parse(Unknown Source)

My code currently works for the ISO. What is the best approach to check if the date is ISO or not?

CodePudding user response:

A lazy way to do that will be by comparing the string length.

private String getFormattedDateTime(String date){
    DateTimeFormatter formatter = null;
    if(date.lenght()>10)
       // initialize formatter for '2022-05-27T17:38:00.000Z'
    else 
       // initialize formatting for '2022-05-27'

    //rest of your code

}

You will be needing 2 formatters though for both ISO and Basic Date.

CodePudding user response:

Don't use a single formatter, use multiple formatters. The problem you have though, is one value is a date value (without time), so it's not possible to convert it to an Instant (I know, I tried

  •  Tags:  
  • java
  • Related