With this overloaded static method, we can specify our own formatter, or we can use one of the supported pre-defined
constants of DateTimeFormatter class which support date-time with an offset id.
package com.logicbig.example.offsetdatetime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
public class ParseExample2 {
public static void main(String... args) {
OffsetDateTime date = OffsetDateTime.parse("2016-10-02T20:15:30+01:00",
DateTimeFormatter.ISO_DATE_TIME);
System.out.println(date);
date = OffsetDateTime.parse("2016-10-03T15:10:40Z",
DateTimeFormatter.ISO_ZONED_DATE_TIME);
System.out.println(date);
date = OffsetDateTime.parse("Wed, 1 Mar 2017 11:05:30 GMT",
DateTimeFormatter.RFC_1123_DATE_TIME);
System.out.println(date);
date = OffsetDateTime.parse("2016-10-02T20:15:30-06:00",
DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(date);
}
}
Output
2016-10-02T20:15:30+01:00
2016-10-03T15:10:40Z
2017-03-01T11:05:30Z
2016-10-02T20:15:30-06:00
package com.logicbig.example.offsetdatetime;
import java.time.OffsetDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class ParseExample3 {
public static void main(String... args) {
OffsetDateTime d = OffsetDateTime.parse("2017-Apr-16 02:09:10 -0500",
DateTimeFormatter.ofPattern("yyyy-MMM-dd HH:mm:ss x"));
System.out.println(d);
}
}
Output
2017-04-16T02:09:10-05:00
package com.logicbig.example.offsetdatetime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class ParseExample4 {
public static void main(String... args) {
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z");
String dateString = "31/Mar/2017:05:16:03 -0700";
OffsetDateTime d = OffsetDateTime.parse(dateString, formatter);
System.out.println(d);
}
}
Output
2017-03-31T05:16:03-07:00