Violetta
Violetta

Reputation: 603

How to save a date in a specific format with timezone in hibernate

Previously, I used to write to the database.

insert into test_table 
    (id, event_date, insert_date) 
values 
    (:id, 
    to_timestamp(:event_date, "YYYY-MM-DD HH24:MI:SS.FF3TZH:TZM"), 
    to_timestamp(:insert_date, "YYYY-MM-DD HH24:MI:SS.FF3TZH:TZM") AT TIME ZONE 'utc')

Now I'm trying to rewrite the insertion into the database using hibernate. I wrote Entity, but I don't know how to specify the correct date format YYYY-MM-DD HH24:MI:SS.FF3TZH:TZM and "YYYY-MM-DD HH24:MI:SS.FF3TZH:TZM" in UTC

@Entity
@Table(name = "test_table")
public class TestTable {
    @Id
    private Long id;

    //?
    private LocalDateTime eventDate;

    //?
    private LocalDateTime insertDate;
}

Also, I'm not sure I've chosen the right type LocalDateTime. The date comes to me as a string.

How do I save the date in the correct format? I use Postgresql

Upvotes: 0

Views: 1296

Answers (1)

Aditya Desai
Aditya Desai

Reputation: 11

To convert String to LocalDateTime you can follow this steps

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");    
LocalDateTime dateTime = LocalDateTime.parse("2022-01-28T14:29:10.212", formatter);

And to convert it into OffsetDateTime you can follow this steps.

ZoneId zoneId = ZoneId.of("UTC");   // Or another geographic: Europe/Paris
ZoneId defaultZone = ZoneId.systemDefault();
ZoneOffset offset = zoneId.getRules().getOffset(dateTime);
OffsetDateTime offsetDateTime = OffsetDateTime.of(dateTime, offset);

Upvotes: 1

Related Questions