Convert Timestamp from db and Timezone column into RFC 3999 format

Yonatan Karp-Rudin :

Before I'll start - I've looked at those answers and didn't got the required answer:

I've currently read from a database 2 column:

  • created_at (a timestamp in which this column was created - for example, 2016-12-23 15:39:15)
  • timezone - the timezone of the timestamp (for example - GMT+01:00).

I need to convert this information into an RFC 3999 (e.g. - 2019-10-02 10:19:23-0800 representation of the time. however, I cannot figure out how to do so since from what I've saw OffsetDateTime expect a different format for the Timezone.

Another option might be to do it on the database level - but I couldn't figure out a way to do this as well...

edwgiz :
...
    ResultSet rs = ...;
    LocalDateTime createdAt = rs.getObject("created_at", LocalDateTime.class);
    String timezoneStr = rs.getString("timezone");

    String createdAtRfc3999 = convert(createdAt, timezoneStr);
...
}

private static final DateTimeFormatter IN_ZONE_OFFSET_FORMATTER = DateTimeFormatter.ofPattern("O");
private static final DateTimeFormatter RFC3999_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ssZ");

public static String convert(LocalDateTime datetime, String strOffset) {
    ZoneOffset zoneOffset = IN_ZONE_OFFSET_FORMATTER.parse(strOffset, ZoneOffset::from);
    return datetime.atOffset(zoneOffset).format(RFC3999_DATE_TIME_FORMATTER);
}

There's shouldn't be a problem to get created_at as LocalDateTime instance from the database whether via pure JDBC or via JPA

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=16574&siteId=1