简体   繁体   中英

Query a mysql DATETIME with a given timezone in Java

I am trying to query a mysql DATETIME from Java. I know the the time zone of the server, but I cannot pull the datetime out with the time zone as I would expect.

ResultSet rs = st.executeQuery(...);

Date d1=rs.getTime(i, Calendar.getInstance(TimeZone.getTimeZone("UTC")));
Date d2=rs.getTime(i, Calendar.getInstance(TimeZone.getTimeZone("PST")));

System.out.println("d1: "+d1.getTime());
System.out.println("d2: "+d2.getTime());

This leaves me with:

d1: 40258000
d2: 40258000

Am I missing something basic here?

ResultSet.getDate() does take the Calendar into account. But I cant use it because it truncates the time info. It's still strange ResultSet.getTime() wouldn't handle any timezone conversions.

The documentation states:

This method uses the given calendar to construct an appropriate millisecond value for the time if the underlying database does not store timezone information.

So perhaps the database does store time zone information in this case?

What does your value in the database look like, and what is it supposed to represent?

An alternative approach would be letting the MySQL server convert the time zone:

SELECT CONVERT_TZ(timefield,'PST','UTC') AS tf

for example would convert the DATETIME value in the field timefield from PST to UTC time (and then returning it as tf ).

getTime on the Date class returns the epoch time according to http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Date.html so it would adjust out your timezone. I think that page implies you should use the timezone adjusted calendar to get your local time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM