I've been banging my head against the wall, trying to get things to work correctly with JDBC and PostgreSQL ... ah, time zones, every programmer's nemesis.
Does this seem familiar?
- Parse "1984-03-02" to a date, say
- Insert that date into the database, as a PostgreSQL date column
- Read the value back from the database
- Print it out and get
A little bit of digging shows that this is a pretty common problem unless both the client and the server are running in the UTC time zone. Now, it goes without saying that you are eligible for institutionalization unless you are running your servers in UTC, and that goes triple for your data store ... but the client? That really shouldn't matter.
Except it does; unless you use the full version of PreparedStatement.setTimestamp(int, Timestamp, Calendar), the PostgreSQL driver uses ... whatever the default client time zone is. Really, that's in the JDBC specification. So much for repeatable behavior!
(ns setup (:import [java.util Date Calendar TimeZone] [java.sql PreparedStatement]) (:require [clj-time.coerce :as coerce] [clojure.java.jdbc :as jdbc])) (extend-type Date jdbc/ISQLParameter (set-parameter [val ^PreparedStatement stmt ix] (let [cal (Calendar/getInstance (TimeZone/getTimeZone "UTC"))] (.setTimestamp stmt ix (coerce/to-timestamp val) cal))))