I am trying to parse a date-time string that does not contain minutes 2019-10-12T07Z.
import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; public class App { public static void main( String[] args ) { // 2019-10-12T07:00:00Z OffsetDateTime offSetDateTime = OffsetDateTime.parse("2019-10-12T07Z"); System.out.println(offSetDateTime.format(DateTimeFormatter.ISO_DATE_TIME)); } }
When I run the above code, it throws the following exception stack trace
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-10-12T07Z' could not be parsed at index 13 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851) at java.time.OffsetDateTime.parse(OffsetDateTime.java:402) at java.time.OffsetDateTime.parse(OffsetDateTime.java:387) at com.test.offset.offset.App.main(App.java:16)
Expected output
2019-10-12T07:00:00Z
Any idea what I should do?
Advertisement
Answer
You have to create custom DateTimeFormatter representing the time and offset.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HHX"); OffsetDateTime odt = OffsetDateTime.parse("2019-10-12T07Z",formatter) ; System.out.println( odt ); //2019-10-12T07:00Z
See that code run at Ideone.com.
2019-10-12T07:00Z
If you want to display the seconds, extract an Instant
to use its toString
method.
Instant instant = odt.toInstant() ; System.out.println( instant ) ; // 2019-10-12T07:00:00Z
2019-10-12T07:00:00Z