田源
2024-03-07 4b4083fd73dc27ece42f4835483565eef0e4f608
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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;
    }
}