Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ResultSet how to getTimeStamp in UTC

Tags:

java

jdbc

The database has data in UTC and when I try to get data

java.util.Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME);
cal.setTime(ts);

Is there anything wrong with this?

like image 326
kal Avatar asked Sep 24 '09 00:09

kal


2 Answers

java.util.Calendar cal = Calendar.getInstance(); 
cal.setTimeZone(TimeZone.getTimeZone("UTC")); 
java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME, cal); 

This should do the trick!

like image 118
Subu Avatar answered Sep 22 '22 04:09

Subu


Your DateFormat instance is most likely displaying the value in local time. When displaying your value, give this a try:

java.util.Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
java.sql.Timestamp ts = resultSet.getTimestamp(PUBLISH_TIME);
cal.setTime(ts);

SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(sdf.format(cal.getTime()));

EDIT: to your comment:

What if I use GMT, would that be an issue in SimpleDateFormat

SimpleDateFormat can use general timezones (GMT +/- n), RFC822, and text ("if they have names" as the JavaDoc states - see this post for info on the names).

like image 24
akf Avatar answered Sep 21 '22 04:09

akf