5

How to convert PostgreSQL timestamp with time zone to Java Instant or OffSetDateTime?

PostgreSQL timestamp with time zone format: 2020-06-18 16:15:38+05:30

Getting the following exception in Java 11.7 - Ubuntu for Instant.parse("2020-06-18 16:15:38+05:30".replace(" ", "T"))

Exception in thread "main" java.time.format.DateTimeParseException: Text '2020-06-18T16:15:38+05:30' could not be parsed at index 19
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.Instant.parse(Instant.java:395)
at OffSetDateTimeExample.main(OffSetDateTimeExample.java:9)

but it works in Java 13.

Any help to make it work in Java 11

5
  • 8
    Don't parse it. Use ResultSet.getObject(..., OffsetDateTime.class) Commented Jun 26, 2020 at 12:04
  • 1
    Do what @a_horse_with_no_name suggested, but if you refuse to do it because you insist on a parsing solution, define a suitable pattern and parse the database column value to an OffsetDateTime by OffsetDateTime odt = OffsetDateTime.parse("2020-06-18 16:15:38+05:30", DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ssxxx"));. Commented Jun 26, 2020 at 12:10
  • 1
    In the database, I have "tstzrange". Commented Jun 26, 2020 at 12:12
  • 4
    That's a range type, not a timestamp with time zone. Probably the easiest way to retrieve that is to use select lower(..), upper(...) to get the two edges of the range as two separate columns. Then use getObject(..., OffsetDateTime.class) on each of them. Commented Jun 26, 2020 at 12:14
  • 3
    Does this answer your question? Postgres - split TSTZRANGE in two columns Commented Jun 26, 2020 at 12:20

1 Answer 1

5

Split the range type value

tstzrange is a range type in Postgres.

Split the PostgreSQL tstzrange in query by calling the lower  and upper functions.

select 
    *, 
    lower(tstzrange) as lower_tstzrange, 
    upper(tstzrange) as upper_tstzrange 
from announcement
;

and use it in Resultset as OffsetDateTime

TstzRange.builder()
    .startDateTime(rs.getObject("lower_tstzrange", OffsetDateTime.class))
    .endDateTime(rs.getObject("upper_tstzrange", OffsetDateTime.class))
            .build()

Thanks to a_horse_with_no_name and Arvind Kumar Avinash for saving my day & learnt splitting range datatypes.

Sign up to request clarification or add additional context in comments.

2 Comments

Great, concise and informative answer. TIL. Thanks.
Spot on! Do not forget to accept it so that future visitors can also use the solution confidently.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.