有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将Oracle的Interval数据类型格式化为HH:MM格式?

我在Oracle DB中有一个表,下面有一列

START_TIME INTERVAL DAY(0) TO SECOND(0)

我正在运行一个基本的select查询来从数据库中获取值。我正在使用JDBC模板和getString(),如下所示

String startTime = rs.getString("START_TIME");

当我在数据库中有+00 11:00:00.000000时,rs.getString("START_TIME")获取0 11:0:0.0

+00 09:30:00.000000它获取0 9:30:0.0但我的要求是11:0009:30

有人能帮我格式化吗

我已经尝试了以下方法:

How to represent Oracle Interval in Java-但我正在使用基于swagger开放API yaml的DTO生成,不知道如何实现这一点。另外,我没有使用hibernate。它是普通的JDBC模板

My previous question-但这对我没有帮助


共 (1) 个答案

  1. # 1 楼答案

    您可以尝试以下变体之一:

    // add this function: it converts intervalDS to Time/Timestamp
        public static Time intervalDStoTime(INTERVALDS intervalds) throws ParseException {
            SimpleDateFormat intervalFormat = new SimpleDateFormat("dd hh:mm:ss.SSS");
            java.util.Date parsedDate = intervalFormat.parse(intervalds.stringValue());
            Time time = new java.sql.Time(parsedDate.getTime());
            // or you can replace previous line with this one if yu will need timestamp:
            // Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
            return time;
        }
    
    //...
    // your code:
        //Original:
        oracle.sql.INTERVALDS startTime = rs.getINTERVALDS("START_TIME");
        System.out.println("Original:" + startTime);
        // 1: interval to time:
        Time time = intervalDStoTime(startTime);
        System.out.println("ToTime: " + time);
        // 2: + format
        System.out.println("ToTime + format: " + new SimpleDateFormat("hh:mm").format(time));
        // 3: format bytes
        byte[] bytes = startTime.toBytes();
        int hour = bytes[4] - 60;
        int minute = bytes[5] - 60;
        String hhmm = String.format("%02d:%02d", hour, minute);
        System.out.println("toBytes + format: " + hhmm);