4

Currently, using JDBC, if I want to set a database column to a timestamp value and have the database interpret it as a UTC timestamp, I would do this:

PreparedStatement pst = connection.prepareStatement(sql);
pst.setTimestamp(1, timestampValue, Calendar.getInstance(TimeZone.getTimeZone("UTC"));

but now I want to do the same thing but for an array of Timestamps:

pst.setArray(1, timestampValues);

where timestampValues is an array of Timestamps (and the database column is of type "timestamp[]" e.g in Postgresql. I don't see where I can specify to the JDBC driver that each Timestamp value in the array has to be treated as UTC?

tsaixingwei
  • 636
  • 9
  • 13

2 Answers2

0

User connection.createArrayOf(..) as described here http://docs.oracle.com/javase/tutorial/jdbc/basics/array.html

Ashwin Jayaprakash
  • 2,168
  • 24
  • 29
0

I believe you will have to set them all to UTC right away. Plus the code below overrides the TimeZone used by your JVM to make it use UTC for everything. Then if you need other than UTC you can use SimpleDateFormat to change it (say for logging).

I referred to the following post for the timezone information.

TimeZone utcTimeZone = TimeZone.getTimeZone("UTC");
TimeZone.setDefault(utcTimeZone);
Calendar calendar = Calender.getInstance(utcTimeZone);

....//set the calendar values here.
//i'll just give you an example with a loop, you'll have to customize.
java.sql.Timestamp [] array = new java.sql.Timestamp [5];
for(int i=0; i < array.lenght; i++) {
  array[i] = new java.sql.Timestamp(calendar.getTimeInMillis());
}

PreparedStatement pst = connection.prepareStatement(sql);
pst.setArray(1, array);
Community
  • 1
  • 1
Chris Aldrich
  • 1,904
  • 1
  • 22
  • 37
  • Yeah, I was afraid that I'd have to do that (i.e. set the timezone to UTC globally for the JVM). Thanks. – tsaixingwei Oct 31 '11 at 09:34
  • You miss spelled `CalendEr` on the third line of your code. I tried to edit but edits need to be at least 6 chars – KNejad Jul 27 '19 at 22:48