W3docs

Converting ISO 8601-compliant String to java.util.Date

To convert an ISO 8601-compliant string to a java.util.Date object, you can use the java.text.SimpleDateFormat class and specify the "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" format, which is the ISO 8601 format for dates with a time and time zone.

To convert an ISO 8601-compliant string to a java.util.Date object, you can use the java.text.SimpleDateFormat class and specify the yyyy-MM-dd'T'HH:mm:ss.SSSZ format.

Here is an example of how to do this:


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

// ...

String dateTimeString = "2022-07-28T13:14:15.123+0100";
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
try {
    Date date = isoFormat.parse(dateTimeString);
} catch (ParseException e) {
    e.printStackTrace();
}

This will parse the ISO 8601-compliant string into a Date object.

Note that the SimpleDateFormat.parse() method can throw a ParseException if the string is not in the correct format, so you should make sure to handle this exception in your code. Also, SimpleDateFormat is not thread-safe, so it should not be shared across multiple threads.

You can also use the java.time.format.DateTimeFormatter class from the Java 8 java.time package to parse the ISO 8601-compliant string into a java.time.OffsetDateTime object. Here is an example:


import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

// ...

String dateTimeString = "2022-07-28T13:14:15.123+01:00";
DateTimeFormatter isoFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
try {
    OffsetDateTime dateTime = OffsetDateTime.parse(dateTimeString, isoFormat);
} catch (DateTimeParseException e) {
    e.printStackTrace();
}

This will parse the ISO 8601-compliant string into an OffsetDateTime object.

Note that the OffsetDateTime.parse() method throws a DateTimeParseException if the string is not in the correct format. You should make sure to handle this exception in your code.

The timezone format differs between the two examples because SimpleDateFormat's Z pattern expects a timezone offset without a colon (e.g., +0100), while DateTimeFormatter.ISO_OFFSET_DATE_TIME expects the strict ISO 8601 format with a colon (e.g., +01:00). For new projects, the java.time API is strongly recommended over the legacy java.util.Date class.