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.
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+01:00";
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = isoFormat.parse(dateTimeString);
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.
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.LocalDateTime
object. Here is an example:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
// ...
String dateTimeString = "2022-07-28T13:14:15.123+01:00";
DateTimeFormatter isoFormat = DateTimeFormatter.ISO_DATE_TIME;
LocalDateTime dateTime = LocalDateTime.parse(dateTimeString, isoFormat);
This will parse the ISO 8601-compliant string into a LocalDateTime
object.
Note that the LocalDateTime.parse()
method does not throw a ParseException
if the string is not in the correct format. Instead, it will throw a java.time.format.DateTimeParseException
if the string is not in the correct format. You should make sure to handle this exception in your code.