Search code examples
javajava-8timezonedate-formattingiso8601

In Java, Can I Convert A Date and Time To An ISO 8601 formatted String Without A Timezone?


A history table of an old source system has 2 fields regarding date/time: a date (ex: 12/20/2017) String and a time (14:33:00) String. I have no timezone information I can use. The web service I'm creating is being consumed by a UI team which wants this information as an ISO 8601 formatted String. I'm using Java 8. Is creating an ISO 8601 formatted String version to return to the UI possible without a timezone?


Solution

  • Yes, you can use DateTimeFormatter ISO_LOCAL_DATE_TIME to format without the time zone:

    String input = "12/20/2017 14:33:00";
    DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");
    LocalDateTime date = LocalDateTime.parse(input, inputFormat);
    String output = DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(date);
    System.out.println(output);
    

    Output:

    2017-12-20T14:33:00