SHARE
TWEET

Untitled

a guest Aug 13th, 2016 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package io.github.picodotdev.blogbitix.datetimedatabase;
  2.  
  3. import java.sql.*;
  4. import java.time.ZoneId;
  5. import java.time.ZonedDateTime;
  6. import java.time.format.DateTimeFormatter;
  7.  
  8. public 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. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top