· 10 years ago · Aug 13, 2016, 06:22 AM
1package io.github.picodotdev.blogbitix.datetimedatabase;
2
3import java.sql.*;
4import java.time.ZoneId;
5import java.time.ZonedDateTime;
6import java.time.format.DateTimeFormatter;
7
8public class Main {
9
10 public static void main(String[] args) throws Exception {
11 Class.forName("org.postgresql.Driver");
12 Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost/user", "user", "user");
13
14 {
15 PreparedStatement create = connection.prepareStatement("CREATE TABLE IF NOT EXISTS date (id SERIAL, date TIMESTAMP, PRIMARY KEY(id))");
16 create.execute();
17
18 PreparedStatement delete = connection.prepareStatement("DELETE FROM date");
19 delete.execute();
20 }
21
22 {
23 PreparedStatement insert = connection.prepareStatement("INSERT INTO date (date) VALUES (?)");
24 ZonedDateTime date = ZonedDateTime.of(2016, 10, 30, 2, 30, 0, 0, ZoneId.of("Europe/Madrid"));
25 System.out.printf("Before database: %s\n", date.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
26
27 insert.setTimestamp(1, Timestamp.valueOf(date.toLocalDateTime())); // !! timezone lost
28 insert.execute();
29 }
30
31 {
32 PreparedStatement select = connection.prepareStatement("SELECT date FROM date");
33 ResultSet rs = select.executeQuery();
34 rs.next();
35 ZonedDateTime date = ZonedDateTime.ofInstant(rs.getTimestamp("date").toInstant(), ZoneId.of("Europe/Madrid"));
36 System.out.printf("After database: %s\n", date.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
37 }
38 }
39}