Monday, September 29, 2014

Postgres, JDBC, Time Zones

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 #inst "1984-03-02T00:00:00.000-00:00"
  • Insert that date into the database, as a PostgreSQL date column
  • Read the value back from the database
  • Print it out and get #inst "1984-03-01T08:00:00Z"
  • Curse!

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!

My solution uses a dash of Joda Time (via clj-time):

This hooks into the clojure.java.jdbc library and extends the logic related to how a PreparedStatement is initialized for execution. It ensures the date or timestamp is interpreted in UTC.

4 comments:

  1. Anonymous5:22 AM

    Adding this to your project.clj seems to work pretty well instead:

    :jvm-opts ["-Duser.timezone=UTC"]

    ReplyDelete
  2. Anonymous5:23 AM

    As an alternative, adding this to your project.clj works welll:

    :jvm-opts ["-Duser.timezone=UTC"]

    ReplyDelete
  3. Anonymous5:24 AM

    :jvm-opts ["-Duser.timezone=UTC"]

    ReplyDelete

Please note that this is not a support forum for Tapestry. Requests for help will be deleted. Please subscribe to the Tapestry user mailing list if you are in need of support, or contact me directly for professional (for pay) support.

Spammers: Don't bother. I delete your comments and it's a waste of time for both of us. 垃圾邮件发送者:不要打扰。我删除您的评论和它的时间对我们双方的浪费