You can parse it with this format: DateTimeFormatter.ISO_OFFSET_DATE_TIME
.
public static void main(String[] args) throws IOException {
String str = "2012-02-22T16:46:28.9870216+00:00";
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println(dtf.parse(str));
}
If you run this code, you will see on the console:
{OffsetSeconds=0, InstantSeconds=1329929188},ISO resolved to 2012-02-22T16:46:28.987021600
Update:
Here is an updated response which shows how to convert the string to a LocalDateTime
and allows date comparisons:
public static void main(String[] args) throws IOException {
String str = "2012-02-22T16:46:28.9870216+00:00";
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
LocalDateTime lds = LocalDateTime.parse(str, dtf);
System.out.println(lds);
String str2 = "2012-02-22T16:46:28.9970430+00:00";
String str3 = "2012-02-22T16:46:29.0270266+00:00";
LocalDateTime lds2 = LocalDateTime.parse(str2, dtf);
LocalDateTime lds3 = LocalDateTime.parse(str3, dtf);
System.out.println(lds2.compareTo(lds3));
System.out.println(lds3.compareTo(lds2));
}
Update 2:
If you want to print out a date in this format you have to use java.time.OffsetDateTime
, like so:
public static void main(String[] args) throws IOException {
OffsetDateTime now = OffsetDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
System.out.println(dtf.format(now));
}
This prints out:
2018-03-18T16:46:46.715Z