title: How to get UTC timestamps from JDBC+postgreSql timestamp?
body: <p>I created a table like like this in PostgreSQL:</p>
  
  <pre class="lang-sql prettyprint-override"><code>create table myTable (
      dateAdded timestamp(0) without time zone null default (current_timestamp at time zone 'UTC');
  )
  </code></pre>
  
  <p>I choose "without time zone" because I know that all timestamps that my application works with are <em>always</em> UTC. As far as I got the documentation the only difference to "with timestamp" is that I can supply values in other time zones which will then be converted to UTC. However I want to avoid such automatic conversions because they could hardly do any good if I know that my values are UTC.</p>
  
  <p>When I add a new record in my test table and view the table's content with pgAdmin I can see that the insertion date has been correctly saved in UTC format.</p>
  
  <p>However when I try to select values using JDBC the value gets 2 hours subtracted. I am located at UTC+2, so it looks like that JDBC assumes that the date in the table is not a UTC timestamp, but a UTC+2 timestamp instead and tries to convert to UTC.</p>
  
  <p>Some googling revealed that the JDBC standard dictates something about conversion to/from the current time zone, but that this could be prevented by supplying a Calander to getTimestamp/setTimestamp calls. However supplying a calendar did not make any difference at all. Here is my MyBatis/Jodatime converter:</p>
  
  <pre class="lang-java prettyprint-override"><code>@MappedTypes(DateTime.class)
  public class DateTimeTypeHandler extends BaseTypeHandler&lt;DateTime&gt; {
      private static final Calendar UTC_CALENDAR = Calendar.getInstance(DateTimeZone.UTC.toTimeZone());
  
      @Override
      public void setNonNullParameter(PreparedStatement ps, int i,
              DateTime parameter, JdbcType jdbcType) throws SQLException {
          ps.setTimestamp(i, new Timestamp(parameter.getMillis()), UTC_CALENDAR);
      }
  
      @Override
      public DateTime getNullableResult(ResultSet rs, String columnName)
              throws SQLException {
          return fromSQLTimestamp(rs.getTimestamp(columnName, UTC_CALENDAR));
      }
      /* further get methods with pretty much same content as above */
  
      private static DateTime fromSQLTimestamp(final Timestamp ts) {
          if (ts == null) {
              return null;
          }
          return new DateTime(ts.getTime(), DateTimeZone.UTC);
      }
  }
  </code></pre>
  
  <p>What's the correct way to get UTC timestamps from JDBC+PostgreSQL timestamp source?</p>