Last active
June 13, 2016 16:24
-
-
Save methylene/2832c881f972324bc3d199413ca493f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package errorist; | |
import org.h2.jdbcx.JdbcConnectionPool; | |
import java.sql.Connection; | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.sql.Statement; | |
import java.time.LocalDate; | |
import java.time.ZoneId; | |
import java.util.Calendar; | |
import java.util.TimeZone; | |
// Maven dependency: com.h2database:h2:1.4.192 | |
public class H2DateFun { | |
private static void insert(JdbcConnectionPool pool, LocalDate born) throws SQLException { | |
try (Connection conn = pool.getConnection(); | |
Statement statement = conn.createStatement()) { | |
statement.execute("CREATE TABLE people (id BIGINT NOT NULL AUTO_INCREMENT," + | |
" born DATE NOT NULL, PRIMARY KEY (id) );"); | |
statement.execute("INSERT INTO people (born) VALUES ('" + born + "')"); | |
} | |
} | |
// Conversion to LocalDate via java.util.Date, as seen in this question: | |
// http://stackoverflow.com/questions/32548331/missed-opportunity-to-fix-jdbc-date-handling-in-java-8 | |
private static LocalDate retrieve(JdbcConnectionPool pool) throws SQLException { | |
try (Connection conn = pool.getConnection(); | |
Statement stmt = conn.createStatement(); | |
ResultSet rs = stmt.executeQuery("SELECT * FROM people limit 1")) { | |
ZoneId utc = ZoneId.of("UTC"); | |
if (rs.next()) { | |
java.sql.Date retrieved = rs.getDate("born", Calendar.getInstance(TimeZone.getTimeZone(utc))); | |
java.util.Date utilDate = new java.util.Date(retrieved.getTime()); | |
return utilDate.toInstant().atZone(utc).toLocalDate(); | |
} | |
} | |
throw new IllegalStateException("No data"); | |
} | |
public static void main(String[] args) throws Exception { | |
JdbcConnectionPool pool = JdbcConnectionPool.create("jdbc:h2:mem:test", | |
"sa", "sa"); | |
LocalDate born = LocalDate.parse("2015-05-20"); | |
insert(pool, born); | |
for (int i : new int[]{-14, 0, 12}) { | |
TimeZone z = TimeZone.getTimeZone(String.format("Etc/GMT%+02d", i)); | |
TimeZone.setDefault(z); | |
LocalDate retrieved = retrieve(pool); | |
System.out.format("%+03d %s%n", i, retrieved); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment