设为首页 收藏本站
查看: 608|回复: 0

[经验分享] Java TimeZone ++: mapping Calendar to Oracle Date or TimeStamp

[复制链接]
YunVN网友  发表于 2016-8-16 07:30:11 |阅读模式
zz Java TimeZone ++: mapping Calendar to Oracle Date or TimeStamp
  

 
  
  (original article : http://blog.sarathonline.com/2009/01/java-timezone-mapping-calendar-to.html )
  In Oracle Database date and timestamp columns can be read in java using s[g]etTimeStamp() methods for storing date and time information. However, they do not save the TimeZone information! The read and write operations are done on java.sql.TimeStamp which is a subclass of java.util.Date. When reading and writing to database, they just write out the *face value* in Java VM's default TimeZone the code is running on. And read the value too 'TO' the java VM's Default TimeZone. So assuming you WriteDate program on a VM in EST and ReadDate program on another VM in PST (or just change system timezone) - You are getting a different *value* in the date Object.

So, How do you tackle this issue. The best way is to set your application to run on a specified (constant) default timezone. As mentioned in the earlier post this can be achieved by TimeZone.setDefault(). If you are unable to do it, JDBC specification allows sql dates to be read and written using a specified calendar. The resultSet.s[g]etTimeStamp method has an overloaded cousin, that takes a Calendar parameter. These methods save the date *face value* into the db after converting it to the timezone of the calendar passed as argument. So if there is a central place, You would want to have code some thing like this.

staticfinalCalendar networkCal =Calendar.getInstance(TimeZone.getTimeZone("EST"));//Writing somewherePreparedStatement ps = conn.prepareStatement("Update datex set dt = ?, tms = ?, faceval =? where id=1");
ps.setDate(1,new java.sql.Date(userDate.getTime()));
ps.setTimestamp(2,newTimestamp(userDate.getTime()),networkCal);//Reading ElsewhereResultSet rs = st.executeQuery("select * from datex where id = 1");
sqlTS = rs.getTimestamp("tms",networkCal);
  
In iBatis (we use iBatis), You can have a TypeHandlerCallback for Calender-TimeStamp mapping

classCalendarTypeHandlerCallbackimplementsTypeHandlerCallback{privatestaticfinalCalendar netWorkCal =Calendar.getInstance(TimeZone.getTimeZone("EST"));publicObject getResult(ResultGetter getter)throwsSQLException{Date date = getter.getDate(netWorkCal);Calendar calendar =null;if(date !=null){
calendar =Calendar.getInstance();
calendar.setTime(date);}return calendar;}publicvoid setParameter(ParameterSetter setter,Object parameter)throwsSQLException{GregorianCalendar calendar =(GregorianCalendar) parameter;
java.sql.Date date =new java.sql.Date(calendar.getTimeInMillis());
setter.setDate(date, netWorkCal);}publicObject valueOf(String s){return s;}}
  A Sample jdbc test case is:

/**
*  Table used:
CREATE TABLE  "DATEX"
("ID" NUMBER(3,0) NOT NULL ENABLE,
"DT" DATE,
"TMS" DATE NOT NULL ENABLE,
"FACEVAL" VARCHAR2(50) NOT NULL ENABLE,
CONSTRAINT "DATEX_PK" PRIMARY KEY ("ID") ENABLE
)
*
* @author spandurangi
*
*/
public class DBTimeStampReadWriteTest extends TestCase {
TimeZone userTz = TimeZone.getTimeZone("IST");
//Used for writing TO and reading FROM RDBMS
static final Calendar networkCal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
String userEntered = "2009-01-31 01:00:01";
/**
* @throws Exception
*/
public void testDirectWriteConvToSTDTz() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
sdf.setTimeZone(userTz);
Date userDate = sdf.parse(userEntered);
System.out.println("========== DATABASE testDirectWriteConvToSTDTz TEST =================");
Connection conn = null;
try {
conn = getConnection();
PreparedStatement ps = conn.prepareStatement("Update datex set dt = ?, tms = ?, faceval =? where id=1");
ps.setDate(1, new java.sql.Date(userDate.getTime()));
ps.setTimestamp(2, new Timestamp(userDate.getTime()), networkCal);
ps.setString(3, userEntered + " p/w " + sdf.getTimeZone().getID());
ps.execute();
Statement st = conn.createStatement();
String SELECT_LATEST = "select * from datex where id = 1";
Calendar ret = printRow(st.executeQuery(SELECT_LATEST));
assertEquals(userDate,ret.getTime());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}

/**
* Run this test seperately with Vm's TZ same after doing the first one
* @throws Exception
*/
public void testDirectReadConvToSTDTz() throws Exception {
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// to compare the same value!!
sdf.setTimeZone(userTz);
Date userDate = sdf.parse(userEntered);
System.out.println("========== DATABASE testDirectReadConvToSTDTz TEST =================");
Connection conn = null;
try {
conn = getConnection();
Statement st = conn.createStatement();
String SELECT_LATEST = "select * from datex where id = 1";
Calendar ret = printRow(st.executeQuery(SELECT_LATEST));
assertEquals(userDate,ret.getTime());
//Comparision may run on any vm!
Calendar org = Calendar.getInstance();
org.setTime(userDate);
ret.setTimeZone(org.getTimeZone());
System.out.println(decorate(org) + " == " + decorate(ret));
assertEquals(decorate(org), decorate(ret));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.close();
}
}
}

private String decorate(Calendar cal) {
FastDateFormat f = FastDateFormat.getInstance("EEE MMM dd HH:mm:ss z yyyy");
return f.format(cal);
}
private Connection getConnection() throws Exception {
Class.forName("oracle.jdbc.OracleDriver");
String url = "jdbc:oracle:thin:@localhost:1521:xe";
return DriverManager.getConnection(url, "sarath", "pass");
}
private Calendar printRow(ResultSet rs) throws Exception {
rs.next();
// JDBC driver reads by face value, loses date info
java.sql.Date sqlDate = rs.getDate("dt");
Calendar cal = Calendar.getInstance();
cal.setTime(sqlDate);
System.out.println("Date Information");
System.out.println(sqlDate + "::" + sqlDate.getTime() + " :: " + cal.getTime() + " :: " + cal.getTimeInMillis()
+ " :: " + decorate(cal));
// JDBC driver reads by face value, applies system tz, (mutates mill
// secs) (WRONG WAY! binding to VM)
Timestamp sqlTS = rs.getTimestamp("tms");
cal = Calendar.getInstance();
cal.setTime(sqlTS);
System.out.println("Timestamp Information from db as it is");
System.out.println(sqlTS + "::" + sqlDate.getTime() + " :: " + cal.getTime() + " :: " + cal.getTimeInMillis()
+ " :: " + decorate(cal));
// JDBC driver reads by face value, applies the supplied tz that is
// supplied (mutates mill secs) (CORRECT! reads in same Tz)
sqlTS = rs.getTimestamp("tms", networkCal);
cal.setTime(sqlTS);
System.out.println("Timestamp Information read with a different Cal (allTimesInTz)");
System.out.println(sqlTS + "::" + sqlDate.getTime() + " :: " + cal.getTime() + " :: " + cal.getTimeInMillis()
+ " :: " + decorate(cal));
return cal;
}
}

  
  If you are using Hibernate, You could use a user type to get similar effect.

Adventurously, I used the TimeZone.setDefault method on non-production systems of an application involving Tomcat, WebLogic a couple of wars and one ear. So far, I have not observed any issues, Google doesnot have any pages that give any known situations either. If I come to know, I will update.

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-258488-1-1.html 上篇帖子: oracle字符串分割和提取函数定义 下篇帖子: IBM小机+ORACLE数据库迅猛提升事物…
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表