javajdbctemplatesql-timestampoffsetdatetime

SQL timestamp not converting to OffsetDateTime


I have a sql timestamp that is being returned from a query in java. I need this date as an OffsetDateTime type, but my attempts to parse it have failed. I've tried the following. What other steps do I need to take?

I'm iterating through the sql response list from my jdbcTemplate. I'm able to access other string rows just fine, but when I try to include this code the query fails. date_column refers to the column in the table and my query is returning the data. It's just not being transformed to OffsetDateTime.

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; OffsetDateTime dateColumn = OffsetDateTime.parse(row.get("date_column").toString(), dateTimeFormatter);

The row.get response returns this date format 2023-07-17 12:22:02.626948


Solution

  • If in the db you don't have stored the offset (as you say, you are returning something like 2023-07-17 12:22:02.626948), then you can obtain a OffsetDateTime only with some assumptions. For example, the following snippet will work if you assume that the LocalDateTime is at UTC:

    String s = "2023-07-17 12:22:02.626948";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.nnnnnn");
    LocalDateTime localDateTime = LocalDateTime.parse(s, dateTimeFormatter);
    OffsetDateTime offsetDateTime = localDateTime.atOffset(ZoneOffset.UTC);