Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i insert timestamp with timezone in postgresql with prepared statement?

I am trying to insert to a timestamp with timezone field of my DB a string which includes date, time and timezone using prepared statement.

The problem is that Timestamp.valueof function does not take into consideration the time zone that the string inludes so it causes an error. The accepted format is yyyy-[m]m-[d]d hh:mm:ss[.f...] which does not mention timezone.

That is the exact code that causes the error:

pst.setTimestamp(2,Timestamp.valueOf("2012-08-24 14:00:00 +02:00"))

Is there any way that i can overcome it?? Thanks in advance!

like image 310
Mike Vasi Avatar asked Dec 03 '12 02:12

Mike Vasi


People also ask

How does Postgres store timestamp with timezone?

In PostgreSQL 2 temporal data types namely timestamp and timestamptz where one is without timezone and the later is with timezone respectively, are supported to store Time and Date to a column. Both timestamp and timestamptz uses 8 bytes for storing timestamp values.

Does Postgres timestamp have timezone?

Introduction to PostgreSQL timestamp The timestamp datatype allows you to store both date and time. However, it does not have any time zone data. It means that when you change the timezone of your database server, the timestamp value stored in the database will not change automatically.

How does timestamp with timezone work?

For timestamp with time zone , the internally stored value is always in UTC (Universal Coordinated Time, traditionally known as Greenwich Mean Time, GMT ). An input value that has an explicit time zone specified is converted to UTC using the appropriate offset for that time zone.


2 Answers

The basic problem is that a java.sql.Timestamp does not contain timezone information. I think it is always assumed to be "local timezone".

On solution I can think of is to not use a parameter in a PreparedStatement, but a timezone literal in SQL:

update foo
  set ts_col = timestamp with time zone '2012-08-24 14:00:00 +02:00'`;

Another possible solution could be to pass a properly formatted String to a PrepareStatement that uses to_timestamp():

String sql = "update foo set ts_col = to_timestamp(?, 'yyyy-mm-dd hh24:mi:ss')"; 
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.setString(1, "2012-08-24 14:00:00 +02:00");
like image 115
a_horse_with_no_name Avatar answered Sep 24 '22 02:09

a_horse_with_no_name


I believe that you could use one more field in your database, which would include the time zone. And calculate the time manually after you get these two fields

like image 44
mariosk89 Avatar answered Sep 24 '22 02:09

mariosk89