package com.vci.server.framework.timer; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import org.hibernate.HibernateException; import com.vci.corba.common.VCIError; import com.vci.server.base.persistence.dao.HibernateCallbackExt; import com.vci.server.base.persistence.dao.HibernateTemplate; public class TimeService { public long getDBTime(){ long dbtime = (Long)new HibernateTemplate().runExt(new HibernateCallbackExt() { @Override public Object execute(Connection cn) throws HibernateException, SQLException, VCIError { // 从DB上取时间 String sql = "select to_char(SYSTIMESTAMP,'YYYY-MM-DD HH24:MI:SS.FF3') from dual"; PreparedStatement pst = null; ResultSet rst = null; long res = System.currentTimeMillis(); try{ // 执行 pst = cn.prepareStatement(sql); rst = pst.executeQuery(); String pattern = "yyyy-MM-dd HH:mm:ss.SSS"; SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date dbtime = new Date(); while(rst.next()){ // DB服务器时间字符串 String dbtimeStr = rst.getString(1); try { // 转换为Date类型,以便取其 long 形式的数据 dbtime = sdf.parse(dbtimeStr); } catch (ParseException e) { // 解析时间出错时,依然取SERVER(不一定是DB服务器)的时间 dbtime = new Date(res); } } // 赋值 res = dbtime.getTime(); }finally{ if(pst != null){ pst.close(); } if(rst != null){ rst.close(); } } return res; } }); return dbtime; } }